1

I have added the custom meta box to my custom post types, but it is not saving content on publish or update button click.

/*
 * Custom book metabox
 */

// Add metabox
function author_book_meta_box_add() {
    add_meta_box( 'author-book', 'Select Book of Author', 'author_book_meta_box', 'awp-author', 'normal', 'high' );
} 
add_action( 'add_meta_boxes', 'author_book_meta_box_add' );

// Metabox callback
function author_book_meta_box( $post ) {
    $values = get_post_custom($post->ID);

    //testing...
    print_r($values);

    $selected = isset( $values['book_meta_box_select'] ) ? esc_attr( $values['book_meta_box_select'][0] ) : '';
    echo "selected".$selected;

    // Add a nonce field so we can check for it later.
    //wp_nonce_field( 'author_book_meta_box_save', 'author_book_meta_box_nonce' );

    ?>
    <p>
    <label for="book_meta_box_select">Select Book: </label>
    <select name='book_meta_box_select'>
        <?php $posts=get_posts(array('post_type' => 'awp-catalogue', 'posts_per_page' => -1)); foreach ($posts as $post): ?>
        <option value="<?php echo esc_attr($post->post_title); ?>" <?php selected( $selected, $post->post_title ); ?>><?php echo esc_html($post->post_title); ?></option>
        <?php endforeach; ?>
    </select>
    </p>
    <?php   
}
function author_book_meta_box_save( $post_id )
{
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'author_book_meta_box_nonce' ) ) return;

    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;

    // Make sure your data is set before trying to save it
    if( isset( $_POST['book_meta_box_select'] ) )
        update_post_meta( $post_id, 'book_meta_box_select', esc_attr( $_POST['book_meta_box_select'] ) );
}
add_action( 'save_post', 'author_book_meta_box_save' );
0

You're update function asks for a request parameter named meta_box_nonce (which is by the way a bad name) but your meta box template does not provide such a field.

It should work if you add the following line right at the end of your function author_book_meta_box():

wp_nonce_field( 'author_book_meta_box_nonce', 'meta_box_nonce' );

Please consider to prefix the request parameter name meta_box_nonce. E.g. your_plugin_meta_box_nonce to avoid collisions with other plugins.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.