WordPress at a glance

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 функция — т.е. её можно заменить из плагина. Это значит, что она будет работать (подключается) только после подключения всех плагинов, а до этого момента функция еще не определена... Поэтому нельзя вызывать эту и зависящие от неё функции прямо из кода плагина. Их нужно вызывать через хук plugins_loaded или позднее, например хук init.

Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.

Is the basis for: wp_nonce_field(), wp_nonce_url()
✈ 1 time = 0.000025s = very fast | 50000 times = 0.21s = very fast | PHP 7.1.1, WP 4.7.2
Hooks from the function

String. The token.


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


#1 Basic Example

echo wp_create_nonce();
// output: c6d25d33be

#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'> ...

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

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


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

Code of wp create nonce: wp-includes/pluggable.php WP 5.2.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();

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

Related Functions

From tag: nonce (security protection defence)

More from tag: Site security (safety)

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register