Problem in custom meta boxes

Okay got the issue, here is the complete code that is saving data. The issues are explained at the bottom:

/**
 * Adds a box to the main column on the Post and Page edit screens.
 */

function nss_mood_add_meta_box() {
    //$id, $title, $callback, $post_type, $context,$priority, $callback_args 
    add_meta_box('nss_mood_id','Set your mood','nss_mood_cb','post');
} 

add_action('add_meta_boxes','nss_mood_add_meta_box');

// Dispalying form and taking input
function nss_mood_cb() {
    global $post;
    echo '<input type="hidden" name="mood_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
    $mood_value = get_post_meta( $post->ID, 'mood_value_key', true );

    // Creating our form
    echo '<p>';
        echo '<label for="mood_value_key">What is your mood today ? </label></br></br>';
        echo '<input type="text" class="widefat" name="mood_value_key" id="mood_value_key" value="' . esc_attr( $mood_value ) . '" />';
    echo '</p>';
}

// Checking value of the form and updating
function save_nss_mood_data($post_id) {

    /*
     * We need to verify this came from our screen and with proper authorization,
     * because the save_post action can be triggered at other times.
     */

    // Check if our nonce is set.
    if ( empty( $_POST['mood_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['mood_meta_box_nonce'], basename(__FILE__)) ) return;

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    // Check the user's permissions.
    if ( isset( $_POST['post_type'] ) ) {

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

    }

    /* OK, it's safe for us to save the data now. */

    // Make sure that it is set.
    if ( ! isset( $_POST['mood_value_key'] ) ) {
        return;
    }

    // Sanitize user input.
    $mood_data = sanitize_text_field( $_POST['mood_value_key'] );

    // Update the meta field in the database.
    update_post_meta( $post_id, 'mood_value_key', $mood_data );
}

add_action('save_post','save_nss_mood_data');

Issues that caused disturbance:

  • Your function nss_mood_cb() needs the $post->ID but there was not $post there. So you need to get the $post variable there, and I did it using global $post.
  • Your nonce sending was not right. You’re creating nonce, but actually not sending to the save function. I added a hidden input there that’s sending the nonce to the save function.
  • In save_nss_mood_data() I checked the nonce in a smarter way.
  • and, as I already commented, your isset( $_POST['mood_field'] ) thing was not right, so I changed it to isset( $_POST['mood_value_key'] ) because that’s actually coming from the nss_mood_cb() callback function.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)