Create custom post type with custom meta boxes
Paste this code in your theme functions.php file to create custom post type “Events” with custom meta box “Event Date”
function custom_event_post_cb() {
$labels = array(
'name' => _x( 'Events', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Event', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Events', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => 'Events',
'labels' => $labels,
'public' => true,
'show_ui' => true,
// 'taxonomies' => array( 'category', 'post_tag' ),
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug' => 'event'),
'query_var' => true,
// 'menu_icon' => 'dashicons-format-gallery',
'supports' => array(
'thumbnail',
'title',
'editor',
'excerpt',
)
);
register_post_type('events', $args);
}
add_action('init', 'custom_event_post_cb');
add_action('add_meta_boxes', 'custom_meta_box');
function custom_meta_box() {
global $post;
if( $post->post_type == 'events' ) {
add_meta_box('events_meta', 'Other Information', 'events_cb', 'events');
}
}
function events_cb() {
global $post;
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$event_dt = get_post_meta($post->ID, 'event_dt', true);
?>
<div class="wrap">
<table class="form-table">
<tbody class="input_fields_wrap_about_video">
<tr>
<th scope="row"><label for="sub_heading">Event Date</label></th>
<td><input name="event_dt" type="date" id="event_dt" value="<?php echo stripcslashes($event_dt);?>" class="regular-text">
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
add_action('save_post', 'metaboxes_save_cb');
function metaboxes_save_cb( $post_id ) {
global $post;
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
$event_dt=$_POST["event_dt"];
if( $post->post_type == 'events' ) {
update_post_meta( $post_id, 'event_dt', stripslashes($event_dt));
}
}