Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 68 ยท Forms, Security and Data Handling

Sanitizing and Validating Input

Learn how to handle WordPress input safely - validate vs sanitize, wp_unslash, sanitize_text_field, sanitize_email, absint, wp_kses, wp_kses_post and esc_url_raw, with tests.

Everything that arrives from outside your code is untrusted: form fields, query strings, AJAX bodies, REST arguments, even values stored by other plugins. Handling that input has two separate jobs. Validation asks "is this acceptable at all?" and rejects what is not. Sanitization takes whatever is left and cleans it so it is safe and tidy to store. WordPress ships a family of helpers for both, and a few habits around $_POST that are easy to forget.

This lesson explains the difference, walks through the most-used sanitizers and wp_kses, and ends with runnable plain-PHP versions with tests, so you can see exactly what each rule keeps and removes. Output is a different job, handled at the other end by escaping.

WordPress cannot run on this site. The real function calls are shown read-only. The runnable code defines simplified stand-ins with the same names and the same general behavior; real WordPress functions handle more cases (character encodings, filters, edge cases), so use the real ones in your plugins.

Validate first, sanitize second

flowchart LR
    A["$_POST value"] --> B["wp_unslash()"]
    B --> C{"Valid?"}
    C -- "No" --> D["Reject with an error message"]
    C -- "Yes" --> E["Sanitize"]
    E --> F["Store or use"]
    F --> G["Escape on output"]

Unslash, validate, sanitize, store. Escaping happens later, when the value is printed.

Validation and sanitization answer different questions:

Validation Sanitization
Question Is this value acceptable? Can I make it safe and clean?
Result Accept or reject A cleaned value
Example "This must be an email address" "Remove illegal characters from this email"
On failure Show an error, stop Silently fix

Prefer to reject bad input when you can, and sanitize what you accept. Sanitizing alone can turn a clearly wrong value into a surprising one: stripping the letters from "abc" for a quantity gives 0, which looks valid. Together they are stronger: is_email() decides whether an address is plausible, and sanitize_email() makes sure what you store contains only legal characters.

Unslash input from $_POST

For historical reasons, WordPress adds backslashes before quotes in $_GET, $_POST, $_COOKIE and $_REQUEST while it loads, which imitates an old PHP feature called magic quotes. Before you use such a value, remove them with wp_unslash(). If you save it with a function that expects slashed data, such as wp_insert_post(), WordPress will unslash it for you, but for everything else you must do it.

PHP
<?php
// real WordPress, read-only
$name = isset( $_POST['name'] )
    ? sanitize_text_field( wp_unslash( $_POST['name'] ) )
    : '';

Notice the order: guard with isset() first, unslash, then sanitize. Doing it the other way round leaves stray backslashes in the stored text.

The sanitizers you will use daily

Function Use it for What it does
sanitize_text_field() Single-line text such as names and titles Removes HTML tags, line breaks, tabs and extra spaces, strips encoded octets like %2F, trims
sanitize_textarea_field() Multi-line text Same cleanup but keeps line breaks
sanitize_email() Email addresses Strips characters that cannot appear in an address; returns '' if it cannot be a valid address
sanitize_key() Slugs, option and array keys Lowercase letters, digits, dashes and underscores only
sanitize_title() URL slugs from titles Turns "Hello World!" into hello-world
absint() IDs and counts Absolute integer (never negative), 0 for junk
intval() / (int) Integers that may be negative Plain cast
esc_url_raw() URLs you store or redirect to Cleans the URL and checks the protocol against an allow list; use esc_url() for output
sanitize_file_name() Uploaded file names Removes unsafe characters
wp_kses() / wp_kses_post() HTML you want to allow in part Strips tags and attributes not on an allow list

Pick the narrowest tool. If a value must be a number, cast it; if it must be one of three options, compare it against the list:

PHP
<?php
$allowed = [ 'draft', 'pending', 'publish' ];
$status  = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : '';

if ( ! in_array( $status, $allowed, true ) ) {
    wp_die( 'Invalid status.', 400 );
}

An allow list beats a clean-up every time: you never need to guess what an attacker could send.

HTML you do want: wp_kses

Some fields must accept markup, for instance a "biography" with links and bold text. wp_kses( $html, $allowed_html ) keeps only the tags and attributes you list and removes everything else, including event handlers like onclick, and it checks protocols in links (so javascript: URLs are dropped).

PHP
<?php
$allowed = [
    'a'      => [ 'href' => true, 'title' => true ],
    'strong' => [],
    'em'     => [],
    'br'     => [],
];

$bio = wp_kses( wp_unslash( $_POST['bio'] ?? '' ), $allowed );

wp_kses_post( $html ) is the same with the tag list that is permitted in post content for authors without the unfiltered_html capability (paragraphs, headings, lists, images, tables and more). Use it for content that should look like a normal post. Use wp_strip_all_tags() when you want no HTML at all, for example in a text excerpt.

Because kses is a sanitizer, the cleaning happens before storage. You still escape on output, which the next lesson covers.

Where WordPress runs these for you

  • Settings API: each register_setting() can take a sanitize_callback (settings API lesson).
  • REST routes: args take validate_callback and sanitize_callback (custom endpoints).
  • Post meta: register_post_meta() accepts sanitize_callback (custom fields).
  • $wpdb->prepare(): protects SQL, but it does not sanitize meaning, and it is not a substitute for any of the above.

Even when a framework hook sanitizes for you, the cost of cleaning twice is tiny and the cost of missing it is high.

Try it: sanitizers with tests

These are simplified stand-ins that behave like their WordPress namesakes on common input. A small check() function plays the part of a unit test, printing PASS or FAIL for each case so you can change a rule and see what breaks.

PHP Plain-PHP sanitizers with tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the "junk stripped" email case. The input is not an address at all, and the sanitizer returns an empty string: sanitizing can end in "nothing usable", which is why the next example validates first.

Try it: validate, then sanitize, then keep the errors

A realistic handler collects all validation problems and only sanitizes when everything is valid. This stand-in simulates $_POST with slashes added (as WordPress does) and runs three submissions through the pipeline. Its wp_kses stand-in is a deliberately small tag filter. It teaches the idea of an allow list but is not a security tool; use the real function.

PHP A validate, unslash and sanitize pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the clean case the onclick attribute is gone and the apostrophe in the name came back without its slash. In the hostile case the script tags disappear (their text, alert(1), stays behind, which is one more reason to escape on output) and the javascript: link loses its href, while the harmless em survives. The invalid case never reaches sanitizing: validation reports all three problems at once.

Common mistakes

  • Skipping wp_unslash(). You store text with extra backslashes and see O\'Neil on the screen.
  • Using the wrong sanitizer. sanitize_text_field() on HTML you meant to keep removes it; wp_kses_post() on a plain name allows markup you did not want.
  • Sanitizing instead of validating. absint( 'abc' ) is 0, which might be a real ID or a real quantity.
  • Confusing sanitizing with escaping. Cleaning on input does not make output safe; always escape at the point of printing.
  • Using esc_url() for stored URLs. It is for output. Use esc_url_raw() when saving or redirecting.
  • Trusting hidden fields and cookies. They are as untrusted as visible fields.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between validation and sanitization?

    Validate to reject unacceptable input, then sanitize what you accept. Output safety is a third step, escaping.
  2. 2. Why call wp_unslash() on values from $_POST?

    WordPress slashes superglobals for historical reasons. Without unslash you store O'Neil instead of O'Neil.
  3. 3. Which function fits a form field that holds a post ID?

    IDs are non-negative integers, so absint() returns exactly that and 0 for junk.
  4. 4. You need to allow only links and bold text in a user's biography. Which is correct?

    wp_kses() keeps only the tags and attributes you list and drops event handlers and unsafe protocols.

Summary

  • Treat all input as untrusted. Validate to reject, then sanitize what you accept.
  • Read superglobals with isset(), then wp_unslash(), then validate and sanitize.
  • Use the narrowest helper: sanitize_text_field(), sanitize_textarea_field(), sanitize_email(), sanitize_key(), absint(), esc_url_raw().
  • Prefer allow lists for values from a fixed set; use wp_kses() and wp_kses_post() when some HTML must stay.
  • Sanitizing does not replace escaping on output.
  • The runnable examples are simplified plain-PHP stand-ins with tests, not the real WordPress functions.

Next: Escaping Output