wp_create_nonce

Home » Functions » wp_create_nonce

If you’re building a WordPress plugin or theme that requires user authentication and security measures, then you may need to generate a nonce. A nonce is a "number used once" and is like a security token that is used to prevent unauthorized use of certain actions or forms.

The wp_create_nonce() function in WordPress generates a unique nonce code with a specific lifespan (usually 24 hours). You can use this code to verify that the user performing a particular action is authorized and that the request was not created by a malicious script or bot.

The function syntax is simple and straightforward:

$nonce = wp_create_nonce( $action );

Here, the $action parameter is a unique string that is used to generate the nonce. You can pass in any string that makes sense to you and that is unique to your plugin or theme.

Here is an example usage code:

$action = 'my_plugin_action';
$nonce = wp_create_nonce( $action );
echo '<input type="hidden" name="my_plugin_nonce" value="' . esc_attr( $nonce ) . '" />';

In this example, we pass the string "my_plugin_action" as the $action parameter. We then generate the nonce, and finally, we output it as a hidden field in an HTML form. When the user submits the form, we can verify the nonce by calling the wp_verify_nonce() function.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.