wp_create_nonce()WP 2.0.3

Creates a cryptographic token for a short amount of time (from 12 to 24 hours).

The token is created as a part of hash from: timestamp|specified $action|user ID|session $token. So if any of the values changes, the token changes too.

It makes no sense to use this function to check the actions of unauthorized users. If the user is not authorized, the values of the user ID|session $token will be empty, which allows to determine the current nonce code.

Use the function after the init hook.

Nonce token lifetime can be changed with a nonce_life filter.

$nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );

Keep in mind, the specified value is divided into 2 parts (like 2 variants): before and after 12 hours. By default the code is created for 24 hours (one day), and when checking the code with wp_verify_nonce(), the function will return either 1 or 2 — depending on which half of the day (the first 12 hours or the second) the token corresponds.

Pluggable function — this function can be replaced from a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Function replacement (override) — in must-use or regular plugin you can create a function with the same name, then it will replace this function.

1 time — 0.000025 sec (very fast) | 50000 times — 0.21 sec (very fast) | PHP 7.1.1, WP 4.7.2
Hooks from the function

Return

String. The token.

Usage

wp_create_nonce( $action );
$action(string|int)
Scalar value to add context to the nonce.
Default: -1

Examples

0

#1 Basic Example

echo wp_create_nonce();
// output: c6d25d33be
0

#2 Creating a nonce token for a form

<?php $nonce = wp_create_nonce('my-nonce'); ?>
<a href='myplugin.php?_wpnonce=<?php echo $nonce ?>&data=mydata'> ...

<?php 
// Where the request will be handled
$nonce = $_REQUEST['_wpnonce'];

if( ! wp_verify_nonce( $nonce, 'my-nonce') ) 
	die( 'Forbidden!' ); 
?>

Changelog

Since 2.0.3 Introduced.
Since 4.0.0 Session tokens were integrated with nonce creation.

wp_create_nonce() code WP 6.5.2

function wp_create_nonce( $action = -1 ) {
	$user = wp_get_current_user();
	$uid  = (int) $user->ID;
	if ( ! $uid ) {
		/** This filter is documented in wp-includes/pluggable.php */
		$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
	}

	$token = wp_get_session_token();
	$i     = wp_nonce_tick( $action );

	return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
}