1

I created a meta box for page see the following code:

add_action('add_meta_boxes', 'add_metaboxes');

function add_metaboxes() {
    add_meta_box(
        'wpt_slider_meta',
        'Add Slider Image',
        'wpt_slider_meta',
        'slider',
        'normal',
        'default'
    );      
}

function wpt_slider_meta() {
    global $post;

    wp_nonce_field(plugins_url(__FILE__), 'meta_slider_noncename');

    $values = get_post_meta($post->ID, '_meta-slider_img', true);

    // Some html and scripts to upload image.
}

add_action( 'save_post', 'save_slider_img' );
function save_slider_img( $post_id ) {

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

     if ( 'slider' == $_POST['post_type']  ) {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return;
    } else {
        if ( !current_user_can( 'edit_post', $post_id ) )
            return;
    }

    if(wp_verify_nonce($_POST['meta_slider_noncename'], plugins_url(__FILE__)) )
    {
        $images = $_POST['meta-slider_img'];
        update_post_meta( $post_id, '_meta-slider_img', $images );
    }
}

I got two warnings when I click on Add new page; except this all code works fine.

Notice: Undefined index: post_type in /var/www/html/transport/wp-content/themes/transport/functions.php on line 192

Notice: Undefined index: meta_slider_noncename in /var/www/html/transport/wp-content/themes/transport/functions.php on line 200

Anyone can help?

1 Answer 1

2

save_post is called when post is inserted or updated. When you access add new post a post is created and inserted into database. That is actually draft. At that time $_POST is blank therefore, you are seeing warnings.

Solution:

The best option is exit the function as soon as you don't find the nonce. And use isset() to check if key is present.

Example:

function save_slider_img( $post_id ) {

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    } 

    if (!isset($_POST['meta_slider_noncename'])) {
        return;
    }

    if(!wp_verify_nonce($_POST['meta_slider_noncename'], plugins_url(__FILE__))) {
        return;
    }

    if ('slider' == $_POST['post_type'] && current_user_can( 'edit_page', $post_id )) { 
        $images = isset($_POST['meta-slider_img']) ? $_POST['meta-slider_img'] : false;
        update_post_meta( $post_id, '_meta-slider_img', $images );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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