• Hi!
    I have made custom post type and now I want some custom meta boxes in that post type. I’ve managed to show custom meta boxes in edit post, but I can’t save the value. I’ve tried some tutorials, no success. I’m new in wordpress so help would be appreciated. Thanks!
    Here is my code:
    This is for displaying meta boxes

    function display_ask_the_docs_meta_box( $ask_the_docs )
    {
    echo '<input type="hidden" name="ask_the_docs_meta_box_nonce"   value="'. wp_create_nonce('ask_the_docs_meta_box'). '" />';
    echo '<label for="question" style="width:100%;">Question:</label><br/>';
    echo '<textarea cols="60" rows="6" name="question" style="width:100%; margin-bottom:20px;"></textarea><br/>';
    echo '<label for="answer" style="width:100%;">Answer:</label><br/>';
    echo '<textarea cols="60" rows="6" name="answer" style="width:100%; margin-bottom:20px;"></textarea><br/>';
    echo '<label for="category" style="width:100%;">Category:</label><br/>';
    echo '<input type="text" name="category" style="width:100%;"/><br/>';
    }

    This is for initializing it

    function my_admin() {
    add_meta_box( 'ask_the_docs_meta_box',
    'Ask The Doctors',
    'display_ask_the_docs_meta_box',
    'ask_the_docs', 'normal', 'high'
    );}

    This is the saving part (that doesn’t work)
    I suppose I’ve failed to hook it to the post. But I’m not quite sure how should I do that.

    function save_ask_the_docs_fields($post_id)
    {
    if (!isset($_POST['ask_the_docs_meta_box_nonce']) || !wp_verify_nonce($_POST['ask_the_docs_meta_box_nonce'], 'ask_the_docs_meta_box'))
    {
    return $post_id;
    }
    if ('post' == $_POST['post_type'])
    {
    if (!current_user_can('edit_post', $post_id))
    {
    return $post_id;
    }
    }
    elseif (!current_user_can('edit_page', $post_id))
    {
    return $post_id;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    {
    return $post_id;
    }
    if(isset($_POST['_question']))
    {
    update_post_meta($post_id, 'question', $_POST['_question'],TRUE);
    }
    else
    {
    delete_post_meta($post_id, 'question');
    }
    if(isset($_POST['_answer']))
    {
    update_post_meta($post_id, 'answer', $_POST['_answer'],TRUE);
    }
    else
    {
    delete_post_meta($post_id, 'answer');
    }
    if(isset($_POST['_category']))
    {
    update_post_meta($post_id, 'category', $_POST['_category'],TRUE);
    }
    else
    {
    delete_post_meta($post_id, 'category');
    }
    }

    And I have this too

    add_action( 'save_post', 'save_ask_the_docs_fields',10,2);
    add_action( 'admin_init', 'my_admin' );

    the custom post type is ask_the_docs

  • The topic ‘Custom meta boxes – saving won't work’ is closed to new replies.