WordPress Security Essentials: Understanding wp_nonce_field() and check_admin_referer()
In WordPress development, securing your forms and requests is critical to prevent malicious exploits like Cross-Site Request Forgery (CSRF). Two functions you’ll see often in this context are:
wp_nonce_field()
check_admin_referer()
Let’s explore what they are, how they work, and how you can use them effectively in your themes and plugins.
🔍 What is a Nonce in WordPress?
A nonce (short for “Number used ONCE”) is a security token. It helps WordPress validate that a request (like submitting a form or clicking a link) actually originated from your site and not from an attacker.
Although it’s called a nonce, it can be used more than once within a time limit (usually 24 hours). Think of it as a temporary, verifiable key to protect actions.
🧱 1. wp_nonce_field() – Generate a Nonce for Your Form
✅ Purpose:
The wp_nonce_field()
function inserts a hidden security field into a form. This field holds a unique nonce token.
Syntax:
wp_nonce_field( $action, $name, $referer, $echo );
Example:
<form method="post">
<?php wp_nonce_field('save_form_action'); ?>
<input type="text" name="custom_data" />
<input type="submit" value="Submit">
</form>
This will generate two hidden inputs:
<input type="hidden" name="_wpnonce" value="...">
<input type="hidden" name="_wp_http_referer" value="/current-page-url">
check_admin_referer() – Verify the Nonce on Form Submission
Purpose:
check_admin_referer()
validates the nonce created by wp_nonce_field()
. It also optionally checks the referer URL for additional verification.
Syntax:
check_admin_referer( $action, $query_arg );
Example:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
check_admin_referer('save_form_action');
// If the nonce is valid, continue processing
$data = sanitize_text_field($_POST['custom_data']);
// Save or process data
}
Real-World Workflow
Step-by-step
- Use
wp_nonce_field('action_name')
inside your form. - On form submission, use
check_admin_referer('action_name')
before processing data.
Behind the scenes
- WordPress generates a nonce tied to the logged-in user + action name.
- The form includes that nonce as a hidden field.
- When the form is submitted, the server checks the nonce’s validity and referer.
What If You Skip These?
If you don’t use nonces in your forms:
- Malicious users can trick others into submitting actions (like deleting data).
- Your plugin/theme becomes vulnerable to CSRF.
- WordPress plugin reviewers may reject your code due to insecure practices.
Best Practices
✅ Always use wp_nonce_field()
for POST forms.
✅ Use check_admin_referer()
(or wp_verify_nonce()
) before processing input.
✅ Don’t hardcode the nonce value or reuse across actions.
✅ Use meaningful action names like delete_myplugin_data
or save_profile_custom
.
Final Thought
Even if you’re building a small form or a single AJAX request, never skip nonce validation. Security in WordPress begins with these simple yet powerful functions.