0
0
Wordpressframework~5 mins

Nonce verification in Wordpress

Choose your learning style9 modes available
Introduction

Nonce verification helps protect your WordPress site from unwanted actions by checking if a request is safe and comes from a trusted source.

When processing form submissions to make sure the request is valid.
When handling AJAX requests to confirm they come from your site.
When performing actions like deleting or updating content to prevent attacks.
When creating custom admin pages that accept user input.
When you want to add an extra layer of security to any user action.
Syntax
Wordpress
<?php
if ( ! isset( $_POST['my_nonce_field'] ) || ! wp_verify_nonce( $_POST['my_nonce_field'], 'my_action' ) ) {
    die( 'Security check failed' );
}
// Continue processing safe request
?>

wp_verify_nonce checks if the nonce is valid for the given action.

Always check the nonce before processing sensitive data.

Examples
Check nonce from a form field named 'nonce' for the action 'save_post'.
Wordpress
<?php
if ( isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'save_post' ) ) {
    // Safe to save post
} else {
    // Invalid nonce
}
?>
Use check_ajax_referer to verify nonce in AJAX requests.
Wordpress
<?php
add_action( 'wp_ajax_my_action', function() {
    check_ajax_referer( 'my_action', 'security' );
    // Process AJAX request safely
} );
?>
Verify nonce passed via URL query before deleting an item.
Wordpress
<?php
if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( $_GET['nonce'], 'delete_item' ) ) {
    wp_die( 'Invalid nonce' );
}
// Proceed with deletion
?>
Sample Program

This example shows a simple form with a nonce field. When the form is submitted, the nonce is checked to make sure the request is safe before processing the username.

Wordpress
<?php
// Generate nonce field in a form
$nonce = wp_create_nonce( 'submit_form' );
?>
<form method="post">
    <input type="hidden" name="form_nonce" value="<?php echo $nonce; ?>">
    <input type="text" name="username" placeholder="Enter username">
    <button type="submit">Submit</button>
</form>

<?php
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
    if ( ! isset( $_POST['form_nonce'] ) || ! wp_verify_nonce( $_POST['form_nonce'], 'submit_form' ) ) {
        echo 'Security check failed';
        exit;
    }
    $username = sanitize_text_field( $_POST['username'] ?? '' );
    echo "Hello, $username! Your form was submitted safely.";
}
?>
OutputSuccess
Important Notes

Nonces in WordPress are not true nonces but tokens that expire after 12-24 hours.

Always use wp_create_nonce to generate and wp_verify_nonce to check.

Never trust user input without nonce verification to avoid security risks.

Summary

Nonce verification protects your site from unauthorized actions.

Use wp_create_nonce to create and wp_verify_nonce to check nonces.

Always verify nonces before processing form or AJAX data.