The nonce is security token which is generated by WordPress to help protect URLs and forms of plugin/theme from misuse.
Nonce is a number. Nonce is very important to use nonce field in forms.
For example :
when you trash or delete a post, WordPress adds a nonce key to the URL like this:
"http://www.sitename.com/wp-admin/post.php?post=82&action=trash&_wpnonce=034e76fca2"
When a URL with a nonce key is executed, it is verify nonce. When nonce is not verified, WordPress returns a 403 Forbidden response and an error message, ‘Are you sure you want to do this?’.
Now we learn how to Generate nonce in WordPress
1) How To generate Nonce?
To create Nonce in WordPress you can use below function, which generates and return a unique value based on the current time.
wp_create_nonce( $actioname );
where, actionname: your nonce action name.
example:
$nonce = wp_create_nonce('user-form');
2) How to add Nonce to URLs?
To pass nonce value in url you can use below function,
wp_nonce_url($actionurl, $action)
- $actionurl : URL in which you want add nonce
- $action : name of action which you want to assign nonce.
Example:
<a href='admin.php?page=demopluginpage&action=delete&recid=13&_wpnonce=<?php echo $nonce ?>'>Delete Me</a>
Second Example:
$nonced_url = wp_nonce_url( 'admin.php?page=demopluginpage&action=delete&recid=13', 'delete_my_rec' ); echo '<a href="'.$nonced_url.'">Delete Me</a>';
3) How to add a nonce to a form?
To add a nonce to a form you can use the below function,
wp_nonce_field( $action, $name, $referer, $echo );
- $action : optional. which is action name.
- $name: optional. which is nonce name.
- $referer : optional. which is set the referer field for validation.
- $echo : optional. which is display or return hidden form field.
example:
<form method="post"><?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' );?> <!-- some inputs here ... --> </form>
4) How to verify a nonce?
To verify nonce use below function,
wp_verify_nonce( 'nonce_name', 'nonce_action' );
example:
if ( isset( $_POST['name_of_nonce_field'] ) && wp_verify_nonce( $_POST['name_of_nonce_field'], 'name_of_my_action' ) ) { // process form data } else { print ‘Sorry, your nonce did not verify. It is a secure WordPress site. go get a coffee !!'; } exit;