WordPress Security

Secure WordPress Code: Sanitizing, Escaping, Nonces and Capability Checks

Secure WordPress Code: Sanitizing, Escaping, Nonces and Capability Checks

When a WordPress plugin vulnerability is published, I usually read the technical details. After years of doing this, I notice the same patterns again and again. A form handler that doesn’t check the user’s permissions. A value from the URL printed straight into the page. A database query built by joining strings. An AJAX action available to anyone, including visitors who aren’t logged in.

These aren’t exotic bugs. They’re basic mistakes, and WordPress provides simple, well-documented functions to prevent every one of them. The developers who made them weren’t careless people; they just didn’t build the habits.

If you write WordPress code, whether plugins, themes or snippets, these habits are essential. Here’s what they are and how to apply them.

The core principle

Never trust data. Treat everything that comes from outside your code as potentially malicious: form fields, URL parameters, cookies, HTTP headers, REST API requests, uploaded files, data from external APIs and even data stored in the database, which may have been put there by an attacker or another plugin.

Then handle that data in three stages:

  1. Validate and sanitize when it comes in.
  2. Check permissions and intent before acting on it.
  3. Escape when it goes out.

Sanitizing input

Sanitization cleans data to make it safe and of the expected type before you use or store it. WordPress provides functions for common data types:

A few notes:

  • wp_unslash removes the slashes WordPress adds to request data for historical reasons. Unslash before sanitizing.
  • Use the most specific function. absint for positive integers, sanitize_email for emails, sanitize_key for internal identifiers.
  • For HTML content, use wp_kses_post to allow the same HTML that’s permitted in post content, or wp_kses with your own allowed list.

Validate against expected values

Sometimes sanitizing isn’t enough. If a value must be one of a fixed set, check it explicitly:

Validation rejects anything unexpected. It’s often stronger than trying to clean bad data.

Escaping output

Escaping makes data safe for the specific place it’s being output. The same value needs different escaping depending on whether it appears in HTML text, an HTML attribute, a URL or JavaScript.

Key rules:

  • Escape late. Escape right at the point of output, not earlier. That way, it’s obvious that every output is escaped, and you don’t accidentally double-escape or miss something.
  • Escape everything, even data you think is safe, like values from your own database or options. Stored data might have been tampered with.
  • Use the right function for the context. esc_html for text, esc_attr for attributes, esc_url for URLs, wp_json_encode for data passed to JavaScript.
  • Translated strings need escaping too. Use esc_html__ and esc_attr__ instead of __ when outputting translatable text.

Passing data to JavaScript deserves care:

Or better, use wp_add_inline_script or wp_localize_script, so data is attached to an enqueued script.

Missing output escaping causes cross-site scripting vulnerabilities, where attackers inject JavaScript that runs in other users’ browsers. If an administrator views an injected page, the script can act with their privileges, creating new admin accounts or installing plugins.

Checking capabilities

Before performing any action, check that the current user is allowed to do it:

Check the specific capability needed, not a role. For actions on specific content, use meta capabilities with the object ID:

A very common mistake is using is_admin() as a security check. is_admin() only tells you whether the current request is for an admin page. It returns true for AJAX requests through admin-ajax.php, even from visitors who aren’t logged in. It says nothing about the user’s permissions.

Verifying intent with nonces

Nonces protect against cross-site request forgery, where an attacker tricks a logged-in user’s browser into submitting a request they didn’t intend, such as deleting content or changing settings.

Add a nonce to forms:

And verify it when processing:

In admin screens, check_admin_referer does the check and stops execution if it fails.

Nonces are not a replacement for capability checks. A nonce proves the request was intended; it doesn’t prove the user is allowed. Always use both.

Also note that WordPress nonces are valid for a period of time, up to 24 hours by default, and are tied to the user and action. They’re not true single-use tokens, but they’re effective against forgery.

Securing AJAX handlers

WordPress AJAX uses two hooks:

  • wp_ajax_{action} for logged-in users.
  • wp_ajax_nopriv_{action} for visitors who aren’t logged in.

Only add the nopriv version if visitors genuinely need the action. Every handler should check a nonce and, for anything sensitive, a capability:

Many serious vulnerabilities come from AJAX handlers that change data or reveal private information without checking capabilities, because the developer assumed only admins would ever call them.

Securing REST API endpoints

Custom REST routes must have a real permission_callback:

Use __return_true only for genuinely public data. Use the args array to validate and sanitize parameters. REST requests authenticated with cookies also require a nonce, which WordPress checks automatically when sent in the X-WP-Nonce header.

Preventing SQL injection

Whenever you query the database with variable data, use $wpdb->prepare:

Placeholders like %d for integers, %s for strings and %f for floats are replaced safely. For table and column names, which can’t be placeholders in older versions, use a fixed list of allowed values rather than user input. Recent WordPress versions also support %i for identifiers.

For LIKE queries, escape the search term with $wpdb->esc_like before adding wildcards:

Where possible, use WordPress’s higher-level functions, like WP_Query, get_posts and get_users, which handle escaping internally.

Handling file uploads

File uploads are one of the most dangerous features. A badly handled upload can let attackers place a PHP file on your server and take it over.

  • Use wp_handle_upload or media_handle_upload rather than moving files yourself.
  • Restrict allowed file types to exactly what you need.
  • Check the file type properly with wp_check_filetype_and_ext, not just the extension in the filename.
  • Store uploads in folders where PHP execution is blocked at the server level.
  • Check capabilities before allowing uploads.

Redirects

When redirecting based on user input, use wp_safe_redirect, which only allows redirects to approved hosts. Plain wp_redirect with an unvalidated URL can create open redirect vulnerabilities used in phishing.

Always call exit after redirecting.

Tools that help

  • PHP_CodeSniffer with WordPress Coding Standards flags missing escaping, unsanitized input and missing nonce checks.
  • Static analysis tools like PHPStan with WordPress extensions catch type errors and risky patterns.
  • Code review: having another developer read your code catches mistakes you can’t see.

A quick secure coding checklist

Before shipping any PHP code that handles requests, I run through a short list:

  • Is every value from $_GET, $_POST, $_REQUEST, $_COOKIE and $_SERVER unslashed and sanitized?
  • Is every value validated against what’s allowed, where a fixed set of values applies?
  • Does every action that changes data check a capability?
  • Does every form and AJAX action verify a nonce?
  • Is every database query with variables prepared?
  • Is every output escaped for its context, right at the point of output?
  • Are AJAX handlers registered for visitors only when visitors truly need them?
  • Do REST routes have real permission callbacks?
  • Are uploads validated and stored where PHP can’t run?
  • Are redirects limited to safe destinations?

It takes a couple of minutes per feature, and it catches the vast majority of the mistakes that turn into published vulnerabilities. Keep the list somewhere visible until the habits become automatic.

Finally, remember that security is a shared habit, not a one-off review. When you change existing code, check that the change hasn’t removed a nonce, a capability check or an escaping function. Many vulnerabilities appear in updates rather than in the original release, because a quick fix bypassed a safeguard that used to be there.

Frequently asked questions

What’s the difference between sanitizing and escaping?

Sanitizing cleans data when it comes in, before you use or store it. Escaping makes data safe when it goes out, for the specific context where it’s displayed. You need both.

Do I need to escape data from my own database?

Yes. Data in the database might have been modified by an attacker, another plugin or a bug. Escaping at output protects you regardless of where the data came from.

Is a nonce enough to secure an action?

No. Nonces verify intent, not permission. Always combine nonces with capability checks.

Why is is_admin() not a security check?

It only checks whether the request is for an admin page, including AJAX requests from anyone. It doesn’t check who the user is or what they’re allowed to do.

Final thoughts

Secure WordPress code comes down to a few consistent habits: sanitize and validate input, escape output for its context, check capabilities before acting, verify nonces for anything that changes data, prepare every database query and handle uploads with extreme care. Build these into every function you write, run automated checks and get your code reviewed. Most plugin vulnerabilities would never have happened if these habits had been followed.