WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp create nonce

Description

Generates and returns a nonce. The nonce is generated based on the current time, the $action argument, and the current user ID.

Usage

<?php wp_create_nonce$action ); ?>

Parameters

$action
(string/int) (optional) Action name. Should give the context to what is taking place. Optional but recommended.
Default: -1

Return Values

(string) 
The one use form token.

Example

In this simple example, we create an nonce and use it as one of the GET query parameters in a URL for a link. When the user clicks the link they are directed to a page where a certain action will be performed (for example, a post might be deleted). On the target page the nonce is verified to insure that the request was valid (this user really clicked the link and really wants to perform this action).

<?php
// Create an nonce for a link.
// We pass it as a GET parameter.
// The target page will perform some action based on the 'do_something' parameter.
$nonce = wp_create_nonce( 'my-nonce' );
?>
<a href='myplugin.php?do_something=some_action&_wpnonce=<?php echo $nonce; ?>'>Do some action</a>

<?php 
// This code would go in the target page.
// We need to verify the nonce.
$nonce = $_REQUEST['_wpnonce'];
if ( ! wp_verify_nonce( $nonce, 'my-nonce' ) ) {
    // This nonce is not valid.
    die( 'Security check' ); 
} else {
    // The nonce was valid.
    // Do stuff here.
}
?>

In the above example we simply called our nonce 'my-nonce'. It is best to choose a name for the nonce that is specific to the action. For example, if we were to create an nonce that would be part of a request to delete a post, we might call it 'delete_post'. Then to make it more specific, we could append the ID of the particular post that the nonce was for. For example 'delete_post-5' for the post with ID 5.

wp_create_nonce( 'delete_post-' . $post_id );

Then we would verify the nonce like this:

wp_verify_nonce( $nonce, 'delete_post-' . $_REQUEST['post_id'] );

In general, it is best to make the name for the action as specific as possible.

Notes

Change Log

Source File

wp_create_nonce() is located in wp-includes/pluggable.php.

Related

Nonce functions: wp_nonce_ays(), wp_nonce_field(), wp_nonce_url(), wp_verify_nonce(), wp_create_nonce(), check_admin_referer(), check_ajax_referer(), wp_referer_field()

Nonce hooks: nonce_life, nonce_user_logged_out, explain_nonce_(verb)-(noun), check_admin_referer

Resources

See also index of Function Reference and index of Template Tags.