How to create Meta Box for custom post type

WordPress Meta Box for custom post type
Some time we needed the custom meta box to add the extra fields with custom post type, There is no need to install the new plugin for meta box. So we can create the new custom meta box using the below code.

add_action( 'admin_init', 'my_admin_movies' );
function my_admin_movies() {
    add_meta_box( 'movies_meta_box', 'Video Detail', 'display_movies_meta_box','movies', 'normal', 'high' );
function display_movies_meta_box( $movies ) {
   echo  '<h4>General Details</h4>
    <table width="100%">
            <td style="width: 25%">Video URL</td>
            <td><input type="text" style="width:425px;" name="meta[videourl]" value="'.esc_html( get_post_meta( $movies->ID, 'videourl', true ) ).'" />

add_action( 'save_post', 'add_movies_fields', 10, 2 );
function add_movies_fields( $movies_id, $movies ) {
    if ( $movies->post_type == 'movies' ) {
        if ( isset( $_POST['meta'] ) ) {
            foreach( $_POST['meta'] as $key => $value ){
                update_post_meta( $movies_id, $key, $value );
} ?>

We can add more then one custom meta boxes using above code except We can to add the more fields in above code.
I have added the Video Url custom code in Movies custom post type.


Leave a Reply