Conflicting save_post functions when passing the post id and saving custom meta boxes for different post types

After doing some more research I found that:

  • Instead of hooking the add_meta_box function into admin_menu it should be hooked into add_meta_boxes
  • Instead of the foreach loop use the update_post_meta function on the save function
  • Instead of using the wp_nonce_field the data can be sanitized using esc_attr and strip_tags
  • To pass the post id to the save meta box function you don’t need to include the additional $post variable
  • You have to add a conditional state for the post type on the save function
  • You have to call global $post on the save function

The new and much simpler code for adding both meta boxes:

add_action( 'add_meta_boxes', 'c3m_sponsor_meta' );

function c3m_sponsor_meta() {
    add_meta_box( 'c3m_sponsor_url', 'Sponsor URL Metabox', 'c3m_sponsor_url', 'sponsor', 'side', 'high' );
}

function c3m_sponsor_url( $post ) {
    $sponsor_url = get_post_meta( $post->ID, '_sponsor_url', true);
    echo 'Please enter the sponsors website link below';
    ?>
        <input type="text" name="sponsor_url" value="<?php echo esc_attr( $sponsor_url ); ?>" />
    <?php
}

add_action( 'save_post', 'c3m_save_sponsor_meta' );

function c3m_save_sponsor_meta( $post_id ) {
    global $post;
    if( $post->post_type == "sponsor" ) {
        if (isset( $_POST ) ) {
            update_post_meta( $post_ID, '_sponsor_url', strip_tags( $_POST['sponsor_url'] ) );
        }
    }
}

add_action( 'add_meta_boxes', 'c3m_video_meta' );        

function c3m_video_meta() {
    add_meta_box( 'c3m_video_embed_code', 'Video Embed Code Meta Box', 'c3m_video_embed_code', 'video', 'normal', 'high' );
}

function c3m_video_embed_code( $post ) {
    $embed_code = get_post_meta( $post->ID, '_embed_code', true);
    echo 'Please enter the video embed code below';
    ?>
        <input type="text" name="embed_code" value="<?php echo esc_attr( $embed_code ); ?>" />
    <?php
}

add_action( 'save_post', 'c3m_save_video_meta' );

function c3m_save_video_meta( $post_id ) {
    global $post;
    if( $post->post_type == "video" ) {
        if (isset( $_POST ) ) {
            update_post_meta( $post_ID, '_embed_code', strip_tags( $_POST['embed_code'] ) );
        }
    }
}

Leave a Comment