What is a Nonce in WordPress?
A nonce (short for "number used once") is a security token in WordPress used for protecting URLs, form submissions, and AJAX requests from malicious access. It generates a unique, random value to verify the request is legitimate and prevent attacks like cross-site request forgery (CSRF).
How Does a Nonce Work in WordPress?
WordPress creates a nonce tied to a specific user and action. When an action (like submitting a form or deleting a post) is taken, WordPress verifies the nonce. If the nonce is invalid, the action will be blocked and a 403 Forbidden response will be returned.
When to Use a Nonce in WordPress
- Form Submissions: Protects data submitted via forms.
- URL Queries: Secures actions passed through URLs such as removing a post.
- Custom Use Cases: Some plugins may have custom use cases for nonces to prevent malicious access.
How to Create a Nonce
WordPress provides several useful built-in methods for creating a nonce— each one is tailored for a specific use case.
- Form Submissions: If you want to add a nonce to protect a form, you can use the built-in function wp_nonce_field(). This will create a hidden field containing the nonce for your form.
- URLs: If you require a nonce for a URL-based action, you can take advantage of the built-in wp_nonce_url() function.
- Custom Use Cases: If your use case doesn't fit the previous two, you can use the built-in function wp_create_nonce().
How to Verify a Nonce
Similar to creating a nonce, WordPress also provides several built-in methods for verifying the nonce you created.
- Admin: If you've created a nonce for an admin action or form, you can use check_admin_referer().
- AJAX Requests: If you're using a nonce as part of an AJAX request, us check_ajax_referer()
- Other Use Cases: If you are using a nonce in a different context, you can always use the wp_verify_nonce() method.