Developer · Guide
Sanitizing and Escaping Data in WordPress

Short answer
Sanitize input when it arrives with the function that fits its type, such as sanitize_text_field for plain text or sanitize_email for an address. Escape output at the moment you print it, using esc_html for text, esc_attr for attributes, esc_url for links, and wp_kses_post when HTML is meant to survive. Never trust input, even from your own database, and escape as late as possible.
Key takeaways
- Sanitize input when it arrives, and escape output when it is printed.
- sanitize_text_field strips tags and cleans plain text in five fixed steps.
- esc_html fits text, esc_attr fits attributes, and esc_url fits every link.
- wp_kses_post allows post HTML, while wp_kses_data allows only comment HTML.
- Escape as late as possible, at the line where the value is printed.
What do sanitizing and escaping mean?
Sanitizing cleans data coming into WordPress, while escaping makes data safe at the moment it is printed to the page.
The Common APIs Handbook states that sanitizing input is the process of securing, cleaning, or filtering input data (checked November 2026).
The Common APIs Handbook states that escaping output is the process of securing output data by stripping out unwanted data, like malformed HTML or script tags, before it renders for the end user (checked November 2026).
The two jobs sit at opposite ends of the data flow. Sanitize when data arrives and before it is stored, then escape when the same data leaves and is shown.
Validation is a third, stricter step. The Common APIs Handbook states that validating input means testing data against a predefined pattern with a clear result: valid or invalid (checked November 2026).
Why must you never trust input data?
Every value that reaches your code from outside it can carry something harmful, including values from your own database.
The Common APIs Handbook states the first rule plainly: do not trust any data, whether user input, third-party APIs, or data in your database, without verification (checked November 2026).
The same page states the working rule that follows from it: always validate and sanitize user input before using it, and escape on output (checked November 2026).
The handbook lists five rules for security-minded code: never trust user input, escape as late as possible, escape everything from untrusted sources, never assume anything, and prefer validation or rejection over sanitization (checked November 2026).
WordPress VIP states the same idea in its guiding principles: $_GET, $_POST, $_REQUEST, and $_SERVER data from untrusted sources, including post meta and options from the database, need validation and sanitizing as early as possible and escaping as late as possible on output (checked November 2026).
Even admins count as untrusted users here. The Common APIs Handbook states that even admins are users, and users will enter incorrect data, either on purpose or by accident (checked November 2026).
How do you sanitize text input?
Sanitize text input with sanitize_text_field, which strips tags and cleans the string in five fixed steps.
The Common APIs Handbook gives a title field as the example: a form posts a title, and the code cleans it with $title = sanitize_text_field( $_POST['title'] ); before saving it with update_post_meta (checked November 2026).
Behind the scenes, the handbook states that sanitize_text_field checks for invalid UTF-8, converts single less-than characters to entities, strips all tags, removes line breaks, tabs and extra white space, and strips octets (checked November 2026).
WordPress VIP adds one more step to the same list: the function also strips percent-encoded characters (checked November 2026).
The VIP docs show the fuller call used in real code, with the value unslashed first:
$title = sanitize_text_field( wp_unslash( $_POST['title'] ?? '' ) );
update_post_meta( $post->ID, 'title', $title );
Sanitize as early as you can, when the value is first assigned to a variable. Waiting until later leaves a window where the raw value can slip into a query, a file name, or a saved option.
A guide on how to enable debug mode in WordPress shows how to surface the warnings that appear when unsanitized input reaches code that expects clean data.
Which sanitize function fits each kind of data?
Pick the sanitize function that matches the data type, since each one keeps only what that type allows.
The Common APIs Handbook lists 21 sanitize functions, from sanitize_email and sanitize_file_name to sanitize_key, sanitize_title, and sanitize_url (checked November 2026).
| Function | Use it for | What it keeps |
|---|---|---|
| sanitize_text_field | Plain text such as titles | Text with no tags or line breaks |
| sanitize_textarea_field | Multi-line text | Text with line breaks kept |
| sanitize_email | Email addresses | Only characters allowed in an email |
| sanitize_url | URLs | A clean URL |
| sanitize_key | Keys and slugs for lookups | Lowercase letters, numbers, dashes, underscores |
| sanitize_hex_color | Color values | A hex color such as a six digit code |
| sanitize_file_name | File names | A safe file name |
| sanitize_title | Post titles turned into slugs | A URL friendly slug |
| wp_kses_post | HTML meant for post content | Only HTML allowed in posts |
Use sanitize_email for an email field and sanitize_text_field for a name field. Learn WordPress states that the sanitization API covers both, and gives exactly that name and email pairing as its example (checked November 2026).
Numbers need a different tool. Cast the value to an integer with (int) or pass it through absint, which the WordPress VIP docs describe as converting a value to a non-negative integer and defaulting to zero for a non-numeric value (checked November 2026).
The VIP docs show the pattern with a ZIP code field: convert with absint, then check that the result has five characters, and save an empty value when it does not (checked November 2026).
When the input must match one of a few known values, check it against that list instead of sanitizing it. The Common APIs Handbook states that data validation should be performed as early as possible, before any actions run on it (checked November 2026).
How do you escape output for each context?
Escape output with the function that matches where the value will appear: HTML body, attribute, URL, script, or textarea.
The Common APIs Handbook states that you must use the most appropriate function for the content and context of what you are echoing, and that you always want to escape when you echo, not before (checked November 2026).
| Function | Use it for |
|---|---|
| esc_html | Text printed inside an HTML element |
| esc_attr | Text printed inside an HTML attribute |
| esc_url | Every URL, including src and href values |
| esc_url_raw | A URL stored in the database |
| esc_js | Text used in inline JavaScript |
| esc_textarea | Text printed inside a textarea |
| esc_xml | Text printed inside XML |
Use esc_html any time a value is cleaned and output to HTML. The handbook example echoes a title through esc_html inside a heading, so any tags in the title show as text instead of running (checked November 2026).
Use esc_url on all URLs, including those in src and href attributes. The handbook example escapes a media URL with esc_url before printing it as an image source (checked November 2026).
Use esc_attr for everything else printed into an attribute, such as a stored CSS class. The handbook example escapes a stored class with esc_attr before printing it as a class value (checked November 2026).
The same context rule sits at the heart of wider web security guidance. OWASP states that the right protection depends on how the data is used, and that each variable in the interface should pass through an output encoding function (checked November 2026).
For numbers, cast at output. The handbook states that (int), absint(), and (float) are all correct and acceptable for integers and floats, while intval() and floatval() are acceptable but outdated PHP4 functions (checked November 2026).
Learn WordPress states that name and email fields pulled from the database should be printed with esc_html, and that an ID should be cast to an integer, in its lesson on secure plugin and theme code (checked November 2026).
When should you use wp_kses?
Use wp_kses when the output is meant to contain HTML, since the plain escape functions would strip it all away.
The Common APIs Handbook states that wp_kses safely escapes all non-trusted HTML, such as post text and comment text, and that it preserves HTML (checked November 2026).
You pass wp_kses the value plus an array of the tags and attributes you allow. The handbook example allows only the link, line break, emphasis, and strong tags, with href and title as the only allowed link attributes, and strips every other tag (checked November 2026).
Two ready-made versions cover the common cases. wp_kses_post allows all HTML permitted in post content, and wp_kses_data allows only the HTML permitted in post comments (checked November 2026).
Use wp_kses_post when you print content a user wrote with formatting. Use esc_html when the value should hold no HTML at all, such as a name or a title.
Some WordPress functions already prepare data for output, so no extra escaping is needed. The handbook states that wp_localize_script needs no escaping, since WordPress will escape the values it passes to scripts (checked November 2026).
Why escape as late as possible?
Escape at the exact line where the value is printed, because anything that happens between an early escape and the output can undo the safety.
The Common APIs Handbook states that it is best to do output escaping as late as possible, ideally as data is being output (checked November 2026).
The handbook gives five reasons: code reviews go faster when safety is visible at a glance, a variable could change between an early escape and the output, late escaping helps automatic code scanning, it keeps code ready for future changes, and it removes doubt for the next person who reads the code (checked November 2026).
The handbook shows the two styles side by side. Escaping early means assigning esc_url and esc_html results to variables, then echoing them later, which forces a reader to hunt for where the escaping happened (checked November 2026).
Escaping late means calling esc_url and esc_html inside the echo line itself, so the safety is visible exactly where the value leaves the code.
When late escaping is not practical, mark the value clearly. The handbook states that you should escape while creating the string and store it in a variable ending in _escaped, _safe, or _clean, such as $variable_escaped (checked November 2026).
A guide on how to run a WordPress security audit covers how to check a whole site for unescaped output and other gaps in one pass.
How do nonces and capability checks fit in?
Sanitizing and escaping protect the data, while nonces and capability checks protect the request itself.
WordPress VIP states that nonces should be used to validate all form submissions, and that capability checks need to validate that users can take the requested actions (checked November 2026).
A nonce proves the form submission came from your site and not from a forged request. A capability check proves the logged-in user is allowed to do the action, such as editing a post or changing a setting.
The VIP docs also warn that client-side validation is for the user benefit only. Server-side validation and sanitization is always needed, since anything sent from a browser can be changed before it arrives (checked November 2026).
Treat these as layers, not substitutes. A valid nonce with unsanitized input is still unsafe, and clean input from a user without permission is still the wrong action.
A guide on how to add security headers to WordPress adds another layer on top of the code-level habits in this guide.
What mistakes should you avoid?
The most common mistake is escaping once and then reusing the value in a different context, such as escaping for HTML and then printing it inside a URL.
Escape for the context where the value lands, every time it lands somewhere new. A value that is safe in a paragraph is not automatically safe in an attribute or a script.
A second mistake is sanitizing on output instead of on input. Sanitizing strips data, so doing it at print time can hide the real value and still leave the stored copy dirty for the next use.
A third mistake is trusting data because it came from the database. Stored values were user input once, and a stored script tag runs just as well as a fresh one when printed without escaping.
A fourth mistake is skipping the check on IDs. Cast IDs to integers with (int) or absint before use, since Learn WordPress shows that an uncast ID posted to a delete callback can remove the wrong record (checked November 2026).
Check plugins you did not write with the same care. A guide on how to check a plugin for vulnerabilities shows how to review third-party code before you trust it on your site.
Frequently asked questions
Which sanitize function should I use for each field?
Use sanitize_text_field for plain text, sanitize_textarea_field for multi-line text, sanitize_email for addresses, sanitize_url for links, and sanitize_key for lookup keys. Cast numbers with (int) or absint. When the value must be one of a few known options, check it against that list and reject anything else.
Is sanitizing enough, or do I still need to escape?
No. Sanitizing cleans data on the way in, before it is stored or used. Escaping secures data on the way out, at the moment it is printed. A value can be sanitized and still need escaping, because the stored copy may be printed in a new context later.
How do I pick the right escape function?
Use esc_html for text inside an element, esc_attr for text inside an attribute, esc_url for every URL, esc_js for inline JavaScript, and esc_textarea for text inside a textarea. When the output should contain HTML, use wp_kses with an allowed tag list, or wp_kses_post for normal post content.
Must I escape data that came from my own database?
Yes. Stored values were user input once, and a script tag saved in the database runs just as well as a fresh one when printed without escaping. The handbook rule is to escape everything from untrusted sources, and it names databases and users as examples.
Can I sanitize once and skip escaping later?
No. Sanitizing removes characters, so it cannot make a value safe for every context. A value that is safe inside a paragraph may still break an attribute or a script. Escape for the exact context where the value lands, at the line where it is printed.
Sources
- Sanitizing Data – Common APIs Handbook WordPress Developer Resources
- Escaping Data – Common APIs Handbook WordPress Developer Resources
- Security – Common APIs Handbook WordPress Developer Resources
- Validating Data – Common APIs Handbook WordPress Developer Resources
- Validating, sanitizing, and escaping WordPress VIP
- Securely developing plugins and themes Learn WordPress
- Cross Site Scripting Prevention Cheat Sheet OWASP
Is your product missing, or something out of date?
Tell us what to add or correct. We read every note and reply when we need a source. A message does not buy a ranking.
Thanks — we review requests within 3 business days.


