What is a nonce in WordPress?

A WordPress nonce (“number used once”) is a token which proves that a request came from your own site, for a specific user and action. It stops CSRF attacks, where another site tricks a logged in user into sending a request. A WordPress nonce is valid for a limited time (12 to 24 hours), it is not truly used only once.

wp_set_current_user( 1 );
$nonce = wp_create_nonce( 'delete_item_5' );
echo 'Right action: ' . var_export( (bool) wp_verify_nonce( $nonce, 'delete_item_5' ), true ) . "\n";
echo 'Other action: ' . var_export( (bool) wp_verify_nonce( $nonce, 'delete_item_6' ), true );
Output

Right action: true
Other action: false

  • Forms: wp_nonce_field( 'action', 'name' ) and check with check_admin_referer().
  • Links: wp_nonce_url( $url, 'action' ).
  • AJAX and REST: send it in the X-WP-Nonce header (created with wp_create_nonce( 'wp_rest' )).

A nonce is not a permission check. Also use current_user_can().


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.