Securing (escaping) Output
Securing output is the process of escaping output data.
Escaping means stripping out unwanted data, like malformed HTML or script tags.
Whenever you’re rendering data, make sure to properly escape it. Escaping output prevents XSS (Cross-site scripting) attacks.
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
Escaping helps securing your data prior to rendering it for the end user. WordPress has many helper functions you can use for most common scenarios.
- esc_attr() – Use on everything else that’s printed into an HTML element’s attribute.
- esc_html() – Use anytime an HTML element encloses a section of data being displayed.
- esc_textarea() – Use this to encode text for use inside a textarea element.
- esc_url() – Use on all URLs, including those in the
hrefattributes of an HTML element.
- esc_url_raw() – Use when storing a URL in the database or in other cases where non-encoded URLs are needed.
- wp_kses() – Use for all non-trusted HTML (post text, comment text, etc.)
- wp_kses_post() – Alternative version of
wp_kses()that automatically allows all HTML that is permitted in post content.
- wp_kses_data() – Alternative version of
wp_kses()that allows only the HTML permitted in post comments.
Pay close attention to what each function does, as some will remove HTML while others will permit it. You should use the most appropriate function to the content and context of what you’re echoing. And remember to escape when you echo, not before.
Most WordPress functions properly prepare data for output, so you don’t need to escape the data again. For example, you can safely call the_title() without escaping.
Escaping with Localization Escaping with Localization
Rather than using
echo to output data, it’s common to use the WordPress localization functions, such as
These functions simply wrap a localization function inside an escaping function:
esc_html_e( 'Hello World', 'text_domain' ); // Same as echo esc_html( __( 'Hello World', 'text_domain' ) );
These helper functions combine localization and escaping:
Custom Escaping Custom Escaping
In the case that you need to escape your output in a specific way, the function wp_kses() (pronounced “kisses”) will come in handy.
This function makes sure that only the specified HTML elements, attributes, and attribute values will occur in your output, and normalizes HTML entities.
$allowed_html = array( 'a' => array( 'href' => array(), 'title' => array(), ), 'br' => array(), 'em' => array(), 'strong' => array(), ); echo wp_kses( $custom_content, $allowed_html );
wp_kses_post() is a wrapper function for
$allowed_html is a set of rules used by post content.