WordPress Nonce
A nonce in WordPress is a security token (a unique string of characters) generated to protect URLs and forms from malicious misuse, such as Cross-Site Request Forgery (CSRF) attacks. The term “nonce” stands for “number used once.” While WordPress nonces are not true cryptographic nonces, they provide an additional layer of validation by ensuring that actions are performed intentionally by authenticated users and not triggered by unauthorized third parties.
How it works
- A nonce is generated using functions like
wp_create_nonce()
orwp_nonce_field()
. - The nonce is sent along with a form or URL as a hidden field or query parameter.
- When the request is submitted, WordPress checks the nonce with
wp_verify_nonce()
orcheck_admin_referer()
. - If the nonce is invalid or expired, the action is rejected.
- By default, WordPress nonces last for 24 hours, though this can be filtered.
Why it matters
Nonces prevent attackers from tricking authenticated users into performing unwanted actions, such as deleting posts, changing settings, or submitting forms. They are essential for securing custom admin pages, AJAX requests, and front-end forms. Without nonces, WordPress sites would be far more vulnerable to CSRF and other injection attacks.
Examples
Adding a nonce to a custom form:
<form method="post">
<?php wp_nonce_field('save_custom_data', 'custom_nonce'); ?>
<input type="text" name="custom_field" />
<button type="submit">Save</button>
</form>
Verifying the nonce when processing the form:
if (isset($_POST['custom_nonce']) &&
wp_verify_nonce($_POST['custom_nonce'], 'save_custom_data')) {
// Safe to process data
} else {
wp_die('Security check failed.');
}