All dynamic data must be correctly escaped for the context where it is rendered.

HTML Attributes

All dynamic data must be escaped with esc_attr() before rendered in an html attribute.

<p title="<?php echo $text; ?>">My Paragraph.</p>

In the example above, we are echoing the value of the $text variable in the title attribute of a paragraph. This is problematic for two reasons:

  • $text may contain malicious data resulting in a XSS exploit.
  • $text may contain valid data that causes the html to break. A lone double quote would result in invalid markup which may cause the page to render poorly.

To ensure the safety and structure of our theme we need to use the WordPress core function esc_attr(). Here’s an example of the above code with esc_attr() used to escape the title attribute.

<p title="<?php echo esc_attr( $text ); ?>">My Paragraph.</p>

esc_attr() is a great catch all function for escaping dynamic data in html attributes, but it is not the only option. In some situations it may be better to use a function that filters more aggressively. Please see the sections below for recommended functions.


Whenever you are rendering a url to the screen its value must be passed through esc_url() first. This will ensure that:

  1. The value is safe to use in HTML attributes.
  2. Special characters, like ampersands, are replaced with HTML entities.

The following example shows a dynamic value rendered inside an html attribute.

<a href="<?php echo $variable; ?>">

Passing the value of $variable through esc_url() before it is rendered will ensure that it is formatted correctly.

<a href="<?php echo esc_url( $variable ); ?>">


If dynamic data is rendered inside an attribute that triggers a JavaScript event, it must be escaped with esc_js(). The following illustrates the incorrect way to render a dynamic value as inline JavaScript.

<a href="#" onclick="alert( '<?php echo $variable; ?>' );">

Passing the value of the variable through esc_js() ensures that the value will be in the correct format before it is rendered to the screen.

<a href="#" onclick="alert( '<?php echo esc_js( $variable ); ?>' );">

While the use of inline JavaScript is perfectly OK, it is recommended that behavior is separated from structure. Moving all JavaScript functionality to a separate file accomplishes this. You can use wp_localize_script() to pass dynamic variables to a standalone JavaScript file. This function will apply esc_js() to all values passed to the $l10n parameter.


Data Validation in the WordPress Codex.