Security is a cornerstone of WordPress development. Whether you’re building a theme, plugin, or custom application, properly sanitizing and escaping data is critical to protecting your site from vulnerabilities like Cross-Site Scripting (XSS) attacks. WordPress security functions help developers handle data safely, including esc_html(), esc_url(), wp_kses(), and sanitize_text_field(). In this guide, we’ll explore these functions in detail, explain their differences, and clarify when to use each one.
Why Security Functions Matter in WordPress
Before diving into the specifics, let’s understand why these functions are essential:
- Prevent XSS Attacks: XSS attacks occur when malicious scripts are injected into web pages. Proper escaping and sanitization ensure that untrusted data can’t execute harmful code.
- Data Integrity: Sanitizing input ensures that only valid data is stored in your database.
- User Trust: Secure websites protect user data and maintain credibility.
Now, let’s break down each function.
1. esc_html(): Escaping HTML Characters
What It Does
esc_html() converts special HTML characters (like <, >, &, “, and ‘) into their corresponding HTML entities. This prevents HTML or JavaScript from being rendered in the browser.
How It Works
For example, if a user inputs <script>alert(‘Hacked!’)</script>, esc_html() will convert it to:
<script>alert('Hacked!')</script>
This code ensures the text is displayed as plain text rather than executed as code.
When to Use esc_html()
- Outputting Text: Use when displaying text in HTML elements (e.g., <div>, <p>, <span>).
- Untrusted Data: Always use for user-generated content (comments, form submissions).
Example
$user_input = '<strong>Hello World</strong>';
echo '<div>' . esc_html($user_input) . '</div>';
Output:
<div><strong>Hello World</strong></div>
The browser displays <strong>Hello World</strong> as plain text.
2. esc_url(): Sanitizing and Escaping URLs
What It Does
esc_url() sanitizes URLs to ensure they’re safe for use in links, redirects, or embeds. It:
- Removes invalid characters.
- Ensures the URL follows a valid format (e.g., http://, https://, mailto:).
- Encodes special characters to prevent injection attacks.
How It Works
If a user provides javascript:alert(‘Hacked!’), esc_url() will sanitize it to an empty string or a safe value, depending on context.
When to Use esc_url()
- Links and Redirects: Use in <a href>, <img src>, or wp_redirect().
- Embedding URLs: For iframes, scripts, or stylesheets.
Example
$user_url = 'javascript:alert("Hacked!");';
echo '<a href="' . esc_url($user_url) . '">Click Me</a>';
Output:
<a href="">Click Me</a>
The malicious JavaScript is stripped, leaving a safe, empty link.
3. wp_kses(): Allowing Controlled HTML
What It Does
wp_kses() (Kses Strips Evil Scripts) allows you to permit specific HTML tags and attributes while stripping others. It’s useful when you need to allow some HTML but want to block potentially dangerous code.
How It Works
You define an array of allowed tags and attributes. For example, you might allow <a> tags with href and title attributes but block <script> tags.
When to Use wp_kses()
- Rich Text Content: For user-generated content that requires HTML (e.g., blog comments, forums).
- Custom Editors: When building interfaces where users can format text.
Example
$allowed_tags = array(
  'a' => array(
    'href' => array(),
    'title' => array()
  ),
  'strong' => array()
);
$user_input = '<a href="https://example.com" onclick="alert(\'Hacked!\')">Safe Link</a>';
echo wp_kses($user_input, $allowed_tags);
Output:
<a href="https://example.com">Safe Link</a>
The onclick attribute is stripped, leaving a safe link.
4. sanitize_text_field(): Sanitizing Text Input
What It Does
sanitize_text_field() sanitizes text input by:
- Removing HTML tags.
- Stripping invalid UTF-8 characters.
- Converting < and > to entities.
- Trimming whitespace.
How It Works
If a user submits <script>alert(‘Hacked!’)</script>, sanitize_text_field() converts it to:
<script>alert('Hacked!')</script>
This code ensures the input is safe to store in the database.
When to Use sanitize_text_field()
- Saving User Input: Use when storing text in the database (e.g., form submissions, post titles).
- Non-HTML Content: For fields where HTML isn’t allowed (e.g., names, email subjects).
Example
$user_input = '<h1>Hello World!</h1> ';
$sanitized_input = sanitize_text_field($user_input);
// Output: "<h1>Hello World!</h1>"
Common Mistakes to Avoid
1 – Using esc_html()
 on URLs:
Incorrect:
<a href="<?php echo esc_html($url); ?>">Link</a>
Correct:
<a href="<?php echo esc_url($url); ?>">Link</a>
2 – Overusing wp_kses()
:
Avoid allowing unnecessary tags. For example, permitting <script>
 in comments could introduce vulnerabilities.
3 – Skipping Sanitization Before Saving:
Always use sanitize_text_field()
 (or similar functions) before storing user input in the database.
Best Practices
- Escape Late, Sanitize Early:
- Sanitize when receiving data (e.g., form submissions).
- Escape when outputting data (e.g., displaying in templates).
- Use Context-Specific Functions:
- URLs: esc_url()
- HTML attributes: esc_attr()
- JavaScript: wp_json_encode()
- Combine Functions When Necessary:
For example, sanitize user input with sanitize_text_field(), then escape it with esc_html() when outputting:
$input = sanitize_text_field($_POST['text']);
echo esc_html($input);
FAQs
Conclusion
Understanding the differences between esc_html(), esc_url(), wp_kses(), and sanitize_text_field() is crucial for building secure WordPress applications. By following the principles of sanitizing input and escaping output, you can protect your site from vulnerabilities while maintaining flexibility. Always choose the right function for the context, and when in doubt, err on the side of caution by stripping unnecessary code. For further reading, explore the WordPress Codex and OWASP XSS Prevention Cheat Sheet.
About the writer
Hassan Tahir wrote this article, drawing on his experience to clarify WordPress concepts and enhance developer understanding. Through his work, he aims to help both beginners and professionals refine their skills and tackle WordPress projects with greater confidence.