When building custom forms, settings pages, or asynchronous AJAX actions in WordPress, security is your primary responsibility. Without proper verification, your site becomes vulnerable to CSRF (Cross-Site Request Forgery) attacks, allowing malicious actors to trick authorized users into performing unintended actions.
Fortunately, WordPress provides a robust built-in security mechanism known as Nonces (number used once), alongside capability checks and strict data sanitization.
In this tutorial, we will walk through how to secure your forms and requests from end to end.
1. Generating and Outputting a Nonce in Forms
A nonce is a unique cryptographic token generated for a specific user session and action. To protect a standard form submission, you generate a nonce using wp_nonce_field() and output it directly inside your HTML <form>.
Add the following code to your template or plugin:
if (!defined('ABSPATH')) {
exit;
}
function wg_render_secure_form() {
?>
2. Verifying Nonces and Capabilities on Submission
When the form is submitted, you must intercept the request, verify the nonce using wp_verify_nonce(), check if the user has the required capabilities, and sanitize the data before processing or saving it.
Add this processing logic to your functions.php or plugin handler:
add_action('admin_post_wg_handle_form', 'wg_process_secure_form_submission');
// For frontend submissions, use: add_action('admin_post_nopriv_wg_handle_form', ...);
function wg_process_secure_form_submission() {
// 1. Verify the nonce
if (!isset($_POST['wg_form_nonce']) || !wp_verify_nonce($_POST['wg_form_nonce'], 'wg_custom_action_name')) {
wp_die(__('Security check failed. Invalid nonce.', 'webgarage'));
}
// 2. Check user capabilities (permissions)
if (!current_user_can('manage_options')) {
wp_die(__('You do not have sufficient permissions to perform this action.', 'webgarage'));
}
// 3. Sanitize and process the input data safely
if (isset($_POST['wg_user_input'])) {
$clean_input = sanitize_text_field($_POST['wg_user_input']);
// Proceed with saving or emailing data...
}
// 4. Redirect back with success message
wp_safe_redirect(add_query_arg('success', 'true', wp_get_referer()));
exit;
}
3. Using Nonces in AJAX Requests
If you are working with asynchronous requests (Fetch API or jQuery AJAX), nonces cannot be passed via hidden form fields easily. Instead, pass them via localized scripts using wp_localize_script(), as we covered in our AJAX file upload tutorial, and verify them in your AJAX handler:
function wg_ajax_security_verification() {
// Check the nonce sent via AJAX headers or POST data
check_ajax_referer('wg_custom_action_name', 'nonce');
// Check user permissions
if (!current_user_can('edit_posts')) {
wp_send_json_error('Unauthorized action.');
}
// Process AJAX request...
wp_send_json_success('Data processed securely!');
}
add_action('wp_ajax_wg_secure_action', 'wg_ajax_security_verification');
Best Practices for WordPress Security
- Never Trust User Input: Always assume incoming data is malicious. Use appropriate sanitization functions (sanitize_text_field(), sanitize_email(), absint()) and validation.
- Always Pair Nonces with Capabilities: Nonces prove who sent the request and when, but they do not prove permissions. Always combine wp_verify_nonce() with current_user_can().
Implementing nonces, capability checks, and data sanitization keeps your custom WordPress solutions secure, robust, and protected against common web vulnerabilities.
Be sure to check out our previous tutorials on WordPress development:
How to Register Custom Post Types & Taxonomies
Modifying WordPress Database Queries with posts_where
Creating Custom Cron Jobs in WordPress with WP-Cron
Need help with your project? We will be happy to help with your project. Feel free to contact us. Just reach out and we will reply soon.