Using WordPress ‘esc_html()’ PHP function

The esc_html() WordPress PHP function helps in safely outputting HTML by escaping HTML entities. This is particularly useful to prevent XSS (Cross-Site Scripting) attacks.

Usage

Here’s a simple way to use the esc_html() function:

$text = '<a href="http://www.example.com/">A link</a>';
$safe_text = esc_html( $text );
echo $safe_text;

In the above code, the output will be the string &lt;a href="http://www.example.com/"&gt;A link&lt;/a&gt; rather than an actual HTML anchor tag.

Parameters

  • $text (string – Required): The text that you want to escape.

More information

See WordPress Developer Resources: esc_html()
Please note that esc_html() avoids double encoding. For instance, if you pass A & B to esc_html(), it will return A & B, not A &amp; B.

Examples

Example 1

Escaping a basic HTML tag:

$text = '<div>Hello, World!</div>';
echo esc_html( $text );

This will output &lt;div&gt;Hello, World!&lt;/div&gt; instead of a div element.

Example 2

Preventing XSS attack:

$user_input = '<script>dangerous_code_here</script>';
echo esc_html( $user_input );

In this case, dangerous script tags input by a user will be neutralized.

Example 3

Working with form data:

$form_data = '<input type="text" name="username">';
echo esc_html( $form_data );

This will output the escaped HTML string of the form data.

Example 4

Avoiding double encoding:

$text = 'A & B';
echo esc_html( $text );

This will output A & B, not A &amp; B.

Example 5

Working with URLs:

$url = '<a href="http://www.example.com/">Visit Example.com</a>';
echo esc_html( $url );

This will escape the URL string, helping to maintain the integrity of your web page.