I’ve read the reference of this function on WordPress but i still don’t understand what this function really does.
I’m reading a tutorial about creating a meta box in wordpress and I have this code inside the function which saves the data:
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
Can someone explain briefly what is the meaning of wp_verify_nonce() ?
The nonce is a ‘number used once’ – a code that WP uses to make sure that POST data is coming from a safe place. This is useful to make sure that your plugin does not end up digesting data from an unsafe source (see Cross-Site Request Forgery).
This blog post by Mark Jaquith is useful for understanding them.
To create a nonce you must give
wp_create_nonce
a certain string, providing the ‘context’ for the nonce. It gives you back a string – the nonce itself. You then include this nonce as part of your POST request. The receiving page should then create a nonce of its own, using the same context, and see if they match up.In this case, the context given is
plugin_basename(__FILE__)
. This will generate the same string whenever it is called from within the same plugin (see here).When your
wp_verify_nonce
recieves a nonce created under the same circumstances as specified by Mark, with the same context string, it returns true.In short:
returns true if wp_verify_nonce returns false.
First argument to
wp_verify_nonce
: the nonce to check. This code gets the nonce out of the post request, stored in the $_POST global.Second argument to
wp_verify_nonce
: the context for generating the new nonce against which the first will be checked.If the nonce doesn’t match, stop executing the current function, returning the variable
$post_id
.