Definition
WordPress Nonces (Numbers Used Once) are security tokens that help protect WordPress sites from malicious attacks like CSRF (Cross-Site Request Forgery). They are temporary, unique codes that verify that a user intended to perform a specific action, ensuring requests come from legitimate sources rather than malicious scripts or unauthorized third parties.
Use Cases & Examples
Form Submissions
Add nonces to custom forms to prevent unauthorized submissions:
// Generate nonce in form
wp_nonce_field('save_user_settings', 'user_settings_nonce');
// Verify nonce on form processing
if (!wp_verify_nonce($_POST['user_settings_nonce'], 'save_user_settings')) {
wp_die('Security check failed');
}
AJAX Requests
Secure AJAX calls by including nonces in JavaScript:
// Localize script with nonce
wp_localize_script('my-script', 'ajax_object', array(
'nonce' => wp_create_nonce('my_ajax_action')
));
// Verify in AJAX handler
if (!wp_verify_nonce($_POST['nonce'], 'my_ajax_action')) {
wp_die('Security check failed');
}
Core Nonce Functions:
wp_create_nonce()
Generates a nonce
wp_verify_nonce()
Verifies a nonce
wp_nonce_field()
Outputs nonce form field
wp_nonce_url()
Adds nonce to URL
check_admin_referer()
Verifies nonce and referrer
Common Misconceptions
“Nonces provide complete security”
Nonces only protect against CSRF attacks. They don’t prevent other security issues like SQL injection, XSS, or unauthorized access. They should be part of a broader security strategy, not the only security measure.
“All WordPress forms automatically have nonce protection”
WordPress core forms include nonces, but custom forms created by themes and plugins need manual nonce implementation. Developers must explicitly add nonce fields and verification.
References & Resources
WordPress Developer Documentation:
Security Best Practices:
Advanced Implementation: