---
name: wp-plugin-security
description: "Security guidelines for WordPress plugin development: sanitization, validation, escaping (PHP and admin JavaScript), nonces, capabilities over objects, multisite boundaries, SQL injection, XSS, CSRF, request headers and the client IP behind proxies, authentication shortcuts, registered meta in REST, and secrets stored in the database. Bundles a release security gate: a procedure and three scripts to run before every release. Use it whenever you write or review plugin code that handles user input, prints dynamic output, registers AJAX or REST endpoints or meta, checks permissions, reads request headers or IP addresses, touches login or two-factor flows, writes files shared by a network, stores copies of configuration, or suppresses PHPCS security sniffs, and whenever a release, a security audit or a reply to the wordpress.org security review is being prepared, even if nobody says the word security. Based on official WordPress Developer Resources and on post-incident reviews of CVE-2026-81754."
compatibility: "WordPress 6.0+ / PHP 7.4+. Applies to plugins, themes, and custom code. The bundled scripts need Node.js, PHP CLI with mbstring, and Python 3."
license: GPL-2.0-or-later
metadata:
author: fernando-tellado
version: "1.3"
---
# WordPress plugin security
## When to use
Use this skill when:
- Developing new WordPress plugins or themes
- Reviewing existing code for security vulnerabilities
- Handling user input (forms, AJAX, REST API)
- Outputting dynamic content to the browser
- Interacting with the database
- Creating admin pages or settings
- Implementing AJAX or REST endpoints
- Processing file uploads
### Scope: audit the surface, not the diff
Reviewing only what changed is how a flaw survives for years while every release passes its security gate. Two rules make the difference:
- **If the change touches an escaper, a validator, a capability check or an `is_*_request()` helper, the unit of review is the whole function and every one of its callers**, not the lines of the diff. Ask "does this function do the right thing for all the contexts it is used in?", not "is this new value handled correctly?". In the incident behind these notes, a review looked at exactly the broken escaper, named it in the release notes and approved it, because it followed the path of the new value (which went to text position) instead of auditing the function and its other eleven uses in attribute position.
- **A review that only follows new data cannot find old flaws.** Rotate: each review takes one whole subsystem and reads it end to end, even if nothing in it changed. And state in writing what the review did **not** cover, so the next one starts there instead of repeating the same blind spot.
- **Checks catch regressions, not original design.** A flaw that was born with the feature never appears in a diff, and no mechanical check has a reason to see it. Whenever a module is touched, ask two questions by hand: which data in the request is chosen by the caller, and which security decisions are taken with it. And when a pattern is learned, sweep the whole codebase for it, not only the place where it showed up.
- **Repairing something that never worked wakes up what was asleep behind it.** A loop that did not iterate, a deletion that did not delete: once it works, every latent flaw in what that code touches becomes real. Audit the revived function as if it were new, and re-read the list of deferred issues, because "this change does not make it worse" stops being true when the change makes a deferred path run for the first time.
- **Changing who can write a value changes every place it is printed.** Giving a role access to the settings, opening a form to customers or visitors, or letting a subsite administrator reach a screen does not touch a single output line, so no diff shows it. Review each output of that value again, asking who writes it now (see "`wp_kses_post()` is a filter, not an escape" below).
## Reference files
The sections below carry the rules. The detail, the longer recipes and the cases behind them are in four files. Load the one that matches the code in front of you.
| File | Read it when |
|------|--------------|
| `references/request-data-and-client-ip.md` | The plugin reads request headers, resolves the visitor's IP address, exempts some requests from a check, serves cached pages, or adds a step to the login |
| `references/registered-meta-and-core-filters.md` | It registers meta, or returns a value through `pre_get_document_title`, `wp_title` or another filter whose result core prints |
| `references/secrets.md` | It stores, exports, emails or diffs configuration files or settings |
| `references/release-gate.md` | A release, a security audit or a reply to the wordpress.org security review is being prepared |
## Release security gate
Before every release, and whenever a security audit is asked for, run the gate in `references/release-gate.md`. It is a procedure with three depths (ordinary change, sensitive change, security plugin or published vulnerability), the mechanical checks with their commands, the questions to answer in writing and the template of the release note.
Two things it rests on: a confirmed finding of medium severity or higher blocks the release, and a gate without a number has not been passed. The release note carries figures and says what was not looked at.
It bundles three scripts. Run `bash scripts/selftest.sh` once in a new environment before trusting them (`PHP=/path/to/php` if PHP is not on the `PATH`).
| Script | Use |
|--------|-----|
| `scripts/test-escapers.js
` | Fails when a JavaScript escaper that does not encode quotes is used inside an attribute |
| `scripts/audit-suppressions.php ` | Lists suppressions of security and SQL sniffs by risk, and fails when any of them has no written justification |
| `scripts/class-symbols.py ` | Fails when a class file uses a `self::` or `$this->` symbol it does not define, which `php -l` does not check |
## Core security principles
### The security mantra
```
Sanitize early
Escape late
Always validate
Never trust user input
```
### Key concepts
1. **Sanitization**: Clean/filter input data as soon as it is received
2. **Validation**: Verify data matches expected format/values (prefer over sanitization)
3. **Escaping**: Secure output data before rendering to prevent XSS
4. **Nonces**: Protect against CSRF attacks on forms and URLs
5. **Capabilities**: Verify user has permission to perform actions
## Sanitization
Sanitize input data immediately upon receipt. Use the most specific function available.
### Sanitization functions
| Function | Use case |
|----------|----------|
| `sanitize_text_field()` | Single-line text input (not URLs, paths or slugs: see the notes below) |
| `sanitize_textarea_field()` | Multi-line text input |
| `sanitize_email()` | Email addresses |
| `sanitize_file_name()` | File names |
| `sanitize_hex_color()` | Color values with hash |
| `sanitize_hex_color_no_hash()` | Color values without hash |
| `sanitize_html_class()` | HTML class names |
| `sanitize_key()` | Keys (lowercase alphanumeric, dashes, underscores) |
| `sanitize_meta()` | Meta values |
| `sanitize_mime_type()` | MIME types |
| `sanitize_option()` | Option values |
| `sanitize_sql_orderby()` | SQL ORDER BY clauses |
| `sanitize_title()` | Titles/slugs |
| `sanitize_title_with_dashes()` | URL-friendly titles |
| `sanitize_user()` | Usernames |
| `sanitize_url()` | URLs for storage |
| `wp_kses()` | HTML with allowed tags |
| `wp_kses_post()` | HTML allowed in posts |
### Sanitization example
```php
// Superglobals arrive slashed: wp_unslash() first, then the most specific sanitizer.
// Sanitize a text field from POST
$title = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );
// Sanitize email
$email = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
// Sanitize URL for database storage
$url = sanitize_url( wp_unslash( $_POST['website'] ?? '' ) );
// Sanitize textarea
$description = sanitize_textarea_field( wp_unslash( $_POST['description'] ?? '' ) );
```
### Important notes on sanitization
- **Never use escape functions for sanitization** - they serve different purposes
- **And never use sanitization as escaping, which is the direction that actually causes breaches.** No `sanitize_*` function prepares a value for a specific output context. `sanitize_text_field()` strips tags, so the value *looks* clean, but it does not touch quotes: a "sanitized" string can still close an HTML attribute and open a new one. Sanitizing is for storing, escaping is for printing, and the correct escape depends on where the value lands. Any review reasoning that stops at "this is already sanitized" has not finished
- **`sanitize_text_field()` and `sanitize_textarea_field()` delete percent-encoded octets.** They do not decode `%C3%AD`, they remove it. A URL, a path, a `REQUEST_URI` or a slug with accents or in a non-Latin script, exactly as the browser writes it, loses its characters: `/categor%C3%ADa/` is stored as `/categora/`, and a slug in Cyrillic comes back empty. Read URLs with `esc_url_raw()` and paths and slugs with `wp_strip_all_tags()`, which WPCS accepts as sanitizers, behind an `is_string()` guard, because `esc_url_raw()` throws a `TypeError` on PHP 8 when it is handed an array
- **`sanitize_text_field()` collapses line breaks into spaces.** For anything multi-line use `sanitize_textarea_field()`
- When using `filter_var()`, always specify a sanitizing filter (not `FILTER_DEFAULT`)
- Process only the specific keys you need, not the entire `$_POST`/`$_GET` array
```php
// A URL keeps its bytes
$target = ( isset( $_POST['target'] ) && is_string( $_POST['target'] ) )
? esc_url_raw( wp_unslash( $_POST['target'] ) )
: '';
// A path or a slug: tags out, %XX octets kept
$source = ( isset( $_POST['source'] ) && is_string( $_POST['source'] ) )
? wp_strip_all_tags( wp_unslash( $_POST['source'] ), true )
: '';
// WRONG for both: the octets are gone before esc_url_raw() sees them
$target = esc_url_raw( sanitize_text_field( wp_unslash( $_POST['target'] ) ) );
```
To cut the path out of a full URL, do it by hand rather than with `wp_parse_url()`. On recent PHP versions `parse_url()` replaces some bytes of raw UTF-8 with an underscore: `/categoría/` comes out intact on PHP 7.4 and broken on PHP 8.5.
```php
// The path of a full URL, without parse_url()
$path = (string) preg_replace( '~^[a-z][a-z0-9+.\-]*://[^/?#]*~i', '', $url );
$path = substr( $path, 0, strcspn( $path, '?#' ) );
```
```php
// CORRECT: Specify sanitizing filter
$post_id = filter_input( INPUT_GET, 'post_id', FILTER_SANITIZE_NUMBER_INT );
// WRONG: No filter or FILTER_DEFAULT does not sanitize
$post_id = filter_input( INPUT_GET, 'post_id' ); // Insecure!
```
## Validation
Validation verifies data matches expected patterns. **Prefer validation over sanitization when possible.**
### Validation philosophies
#### Safelist (recommended)
Accept only known, trusted values:
```php
$allowed_values = array( 'draft', 'pending', 'publish' );
// Use strict comparison (third parameter = true)
if ( in_array( $status, $allowed_values, true ) ) {
// Valid
} else {
wp_die( 'Invalid status' );
}
```
#### Format detection
Test data format and reject if invalid:
```php
// Check alphanumeric only
if ( ! ctype_alnum( $data ) ) {
wp_die( 'Invalid format' );
}
// Check against regex
if ( ! preg_match( '/^\d{5}(-\d{4})?$/', $zip_code ) ) {
wp_die( 'Invalid ZIP code format' );
}
```
#### Type checking
Always use strict comparison (`===`) to prevent type juggling attacks:
```php
// CORRECT: Strict comparison
if ( 1 === $user_input ) {
// Exactly integer 1
}
// WRONG: Loose comparison - "1 malicious" == 1 evaluates to true
if ( 1 == $user_input ) {
// Vulnerable!
}
```
### Validation functions
| Function | Purpose |
|----------|---------|
| `is_email()` | Validate email format |
| `term_exists()` | Check if taxonomy term exists |
| `username_exists()` | Check if username exists |
| `validate_file()` | Validate file path (not existence) |
| `is_array()` | Check if value is array |
| `absint()` | Return absolute integer |
| `in_array( $val, $arr, true )` | Check value in array (strict) |
### Validation example
```php
function ayudawp_is_valid_us_zip( string $zip ): bool {
if ( empty( $zip ) ) {
return false;
}
if ( strlen( trim( $zip ) ) > 10 ) {
return false;
}
if ( ! preg_match( '/^\d{5}(-?\d{4})?$/', $zip ) ) {
return false;
}
return true;
}
// Usage
$zip = isset( $_POST['zip'] ) ? sanitize_text_field( wp_unslash( $_POST['zip'] ) ) : '';
if ( ayudawp_is_valid_us_zip( $zip ) ) {
// Process valid ZIP
}
```
## Escaping
Escape output data **as late as possible**, immediately when echoing.
### Escaping functions
| Function | Use case |
|----------|----------|
| `esc_html()` | Text inside HTML elements |
| `esc_attr()` | Values inside HTML attributes |
| `esc_url()` | URLs in href, src attributes |
| `esc_url_raw()` | URLs for database storage (NOT escaping) |
| `esc_js()` | Inline JavaScript values |
| `esc_textarea()` | Content inside textarea |
| `esc_xml()` | XML content |
| `wp_kses()` | HTML with custom allowed tags |
| `wp_kses_post()` | HTML written by someone who has `unfiltered_html`, or markup the plugin builds from escaped values. Not for text anyone else stored: it keeps `div`, `id` and `class` |
| `wp_kses_data()` | HTML allowed in comments |
### Escaping examples
```php
// Text inside HTML element
// URL in attribute
Link
// Value in attribute
// Image source
// Inline JavaScript
// Textarea content
// HTML written by an author who has unfiltered_html (preserves allowed HTML)
```
### Escape late pattern
Always escape at the point of output:
```php
// WRONG: Escaping early
$url = esc_url( $url );
$text = esc_html( $text );
echo '' . $text . '';
// CORRECT: Escaping late
echo '' . esc_html( $text ) . '';
```
### Echoing the return value of a helper that already escapes
The wordpress.org review team **rejects** `echo my_helper()` even if `my_helper()` already escapes every value internally. Late escaping must be visible at the `echo` call site. There are three valid options depending on what the helper returns:
```php
// HELPER RETURNS SIMPLE HTML THE PLUGIN BUILT ITSELF (spans, links, basic tags,
// every value escaped inside). Wrap the echo in wp_kses_post():
echo wp_kses_post( ayudawp_render_status_badge( $post_id ) );
// HELPER RETURNS HTML THAT wp_kses_post() WOULD STRIP (forms, inputs, selects, buttons)
// Refactor the helper to echo directly (void return) and keep a string wrapper
// only for callers that genuinely need a return value (shortcodes that return).
function ayudawp_render_form( $args = array() ) {
// ... uses esc_attr, esc_html, esc_url internally, but echoes the markup ...
?>
array( 'name' => true, 'id' => true, 'class' => true ),
'option' => array( 'value' => true, 'selected' => true ),
);
echo wp_kses( wp_dropdown_pages( array( 'echo' => 0, /* ... */ ) ), $allowed );
```
The "escaped internally" comment with a `phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped` is a **rejection trigger** in the manual review, regardless of whether the helper does escape correctly. Refactor instead of suppressing.
The `wp_kses_post()` wrap is safe in the first case because the plugin wrote the markup and escaped each value inside it. It stops being safe when the helper passes through text that someone else stored. Then that text goes through `esc_html()` inside the helper, or the wrap is a `wp_kses()` with a short list (see the next sections).
### Escaping with localization
Use combined escape + localization functions:
```php
// Escape + translate
echo esc_html__( 'Hello World', 'text-domain' );
esc_html_e( 'Hello World', 'text-domain' );
// With context
echo esc_html_x( 'Post', 'noun', 'text-domain' );
// For attributes
echo esc_attr__( 'Submit', 'text-domain' );
esc_attr_e( 'Submit', 'text-domain' );
```
Available combined functions:
- `esc_html__()`, `esc_html_e()`, `esc_html_x()`
- `esc_attr__()`, `esc_attr_e()`, `esc_attr_x()`
### Important escaping notes
- **Never use `__()` or `_e()` without escaping** - they do not escape output
- **`esc_url_raw()` is NOT an escaping function** - it's for sanitizing URLs for storage
- For HTML output use `wp_kses()` with an allowlist, or `wp_kses_post()` only when whoever wrote that HTML has `unfiltered_html`. `esc_html()` does not keep HTML: it encodes the tags, which is what you want for plain text
- When escaping HTML attributes, escape the entire value, not parts
```php
// CORRECT: Escape the whole attribute value
echo '
';
// WRONG: Escaping parts separately
echo '
';
```
### A dynamic tag name needs an allowlist, not an escape
`esc_attr()` protects a value inside quotes. In tag-name position there are no quotes, and it does not encode spaces or `=`, so a value such as `img src=x onerror=alert(1)` builds a whole new element. No sniff flags it, because the output is "escaped".
```php
// WRONG: a shortcode attribute chooses the element
echo '<' . esc_attr( $tag ) . ' class="title">' . esc_html( $text ) . '' . esc_attr( $tag ) . '>';
// CORRECT: only known tags reach that position
$allowed = array( 'h2', 'h3', 'h4', 'p', 'div', 'span' );
$tag = in_array( $tag, $allowed, true ) ? $tag : 'div';
printf( '<%1$s class="title">%2$s%1$s>', tag_escape( $tag ), esc_html( $text ) );
```
In one audited plugin this was XSS reachable by a contributor through a shortcode attribute, and an external scanner found it before the maintainer did.
### Values core does not escape for you
"Whoever prints it will escape it" does not finish a review, in the same way that "it is already sanitized" does not. The escaping of the document title is a callback that core hooks on the `document_title` filter at priority 10, not a line inside `wp_get_document_title()`. A value returned through the `pre_get_document_title` short-circuit, or added on `document_title` or `wp_title` at priority 10 or above, is printed raw inside ``. Priority 10 is the default: only a callback hooked below it runs before core's `esc_html`. Escape it in the plugin.
The table of which entry points are escaped, the emitters and how to check it against the installed core: `references/registered-meta-and-core-filters.md`.
### `wp_kses_post()` is a filter, not an escape
`wp_kses_post()` keeps whatever an author may put in a post: `div`, `span`, `id`, `class`, `style` and the rest. That is right for HTML written by someone who already has `unfiltered_html`, and for markup the plugin builds itself with every value escaped inside. For text stored by anyone else it lets a stored attack through. That covers a visitor on a public form, a customer, a role the plugin grants access to, and the administrator of a subsite, who does not have `unfiltered_html` on a multisite network.
- **The sanitizer does not stop it.** `sanitize_text_field()` and `sanitize_textarea_field()` leave `< div id=x>` alone when a space, a tab or a carriage return follows the `<`, because `strip_tags()` sees no tag there. kses accepts that whitespace and rebuilds a real `
`, both when `wp_insert_post()` stores the text for a user without `unfiltered_html` and when `wp_kses_post()` prints it. A newline right after the `<` is escaped by the sanitizer itself (measured on WordPress 7.1.5).
- **An `id` or a `class` is enough.** Core admin scripts act on elements they expect to find in the page. `tags-box.js` reads the `id` of a `.tagsdiv` and concatenates it into HTML, on the post editor and on the WooCommerce order screen with HPOS. No `