wp_verify_nonce

Home » Functions » wp_verify_nonce

WordPress is an open-source content management system that comes with a lot of useful functions. One such function is wp_verify_nonce().

Nonce is a security measure used to prevent unauthorized access or misuse of certain functionalities in WordPress like form submission, URL requests, etc. wp_verify_nonce() checks if a nonce is valid and not expired. It returns either true or false based on its validity.

This function is particularly useful for developers who want to add security measures to their custom WordPress code. It checks if the nonce exists and matches the expected pattern. If the nonce is invalid or expired, the function will return false.

Here’s an example usage code:

Suppose you have a form that you want to secure with a nonce. You can generate a nonce using wp_create_nonce() function and pass it along with the form data. When the form is submitted, you can use wp_verify_nonce() to validate the nonce and ensure that the form was submitted by an authorized user.

// Generate a nonce
$nonce = wp_create_nonce( 'my-form' );

// Create a form with the nonce
$form = '<form method="post">';
$form .= '<input type="text" name="name">';
$form .= '<input type="hidden" name="my-form-nonce" value="'. $nonce .'">';
$form .= '<input type="submit" value="Submit">';
$form .= '</form>';

echo $form;

// Verify the nonce
if ( isset( $_POST['my-form-nonce'] ) && wp_verify_nonce( $_POST['my-form-nonce'], 'my-form' ) ) {
    // Process the form data
    $name = $_POST['name'];
    // ...
} else {
    // Invalid nonce
    die( 'Security check failed' );
}

In this example, we’re generating a nonce using the wp_create_nonce() function and adding it to the form. When the form is submitted, we’re checking if the nonce exists and is valid using wp_verify_nonce(). If the nonce is valid, we’re processing the form data. Otherwise, we’re showing an error message.

Learn More on WordPress.org

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