verification wordpress wp_verify_nonce

I am trying to add a custom meta box with fields to a custom post type i created, using the following tutorial: Creating a metabox in wordpress
. It all works fine, but what bothers me is the error message the moment i start a new custom post type post.

When I click new on my custom created post type portfolio, i get this message

Read More

Notice: Undefined index: mytheme_meta_box_nonce in /home/jellyf1q/public_html/test/webfanatics/wp/wp-content/themes/thewebfanatics/cpt/portfolio.php on line 140

The functions further work fine, and once i updated it, leave the post and come back to it to edit it, the message is gone.

Line 140 refers to the nonce. It checks if the date comes from the edit post with propper authorization. Here is the code for that line:

function mytheme_save_data($post_id) {
    global $meta_box;

// verify nonce
    if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }
    .... more code ....
}

My assumption is that when I create a new post the nonce for the meta box is not created yet, thus cant be checked, or am i wrong here? And is there a solution for this error message?

I know i can turn of the debug mode for wordpress, but i am looking more for a solution in this case.

Related posts

1 comment

  1. Change your code as below, just check if $_POST['mytheme_meta_box_nonce'] is set.

    function mytheme_save_data($post_id) {
        global $meta_box;
    
        // verify nonce
        if (isset($_POST['mytheme_meta_box_nonce']) && !wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) {
            return $post_id;
        }
        .... more code ....
    }
    

Comments are closed.