Escaping
Escaping in WordPress is the process of preparing and securing data before outputting it to the browser. While sanitization cleans data before it’s saved, escaping ensures that data is safe when displayed on a page, preventing malicious code (like injected JavaScript) from executing in the user’s browser. WordPress provides a wide set of escaping functions tailored to different contexts, making it easier to safely output data in HTML, URLs, attributes, or JavaScript.
How it works
- Escaping converts special characters into safe representations so they are displayed as text instead of being executed.
- Common escaping functions in WordPress include:
esc_html()
→ escapes text for use in HTML.esc_attr()
→ escapes values used in HTML attributes.esc_url()
→ escapes URLs before output.esc_js()
→ escapes strings for safe use in JavaScript.wp_kses()
→ allows only specific HTML tags/attributes.
- Best practice: escape late → only when sending data to the browser, never when storing it.
Why it matters
Without escaping, attackers could inject harmful scripts (XSS attacks), manipulate links, or even take control of user sessions. Escaping ensures that even if malicious content finds its way into the database, it won’t execute in the frontend. This is essential for protecting both site users and administrators.
Examples
Escaping user-submitted content in a template:
<p><?php echo esc_html($username); ?></p>
Escaping a URL for use in a link:
<a href="<?php echo esc_url($profile_url); ?>">Profile</a>
Escaping values inside attributes:
<input type="text" value="<?php echo esc_attr($custom_value); ?>">