Using WordPress ‘esc_html()’ PHP function

The esc_html() WordPress PHP function is used to safely escape HTML characters in a string, preventing potential security vulnerabilities like XSS attacks.

Usage

$safe_text = esc_html( $text );
// your custom code here
return $safe_text;

Output: A safely escaped string

Parameters

  • $text (string) – The text to be escaped for use in HTML.

More information

See WordPress Developer Resources: esc_html()

Examples

Escape a string for display in HTML

Prevent HTML tags from being rendered in the output.

$unsafe_text = "<script>alert('Hello');</script>";
$safe_text = esc_html( $unsafe_text );
echo $safe_text;

Output: <script>alert(‘Hello’);</script>

Escape user input from a form

Prevent malicious code from being executed when displaying user input.

$user_input = $_POST['user_input'];
$safe_input = esc_html( $user_input );
echo $safe_input;

Output: Safely escaped user input

Escape a URL as plain text

Display a URL as plain text without making it a clickable link.

$url = "https://www.example.com";
$safe_url = esc_html( $url );
echo $safe_url;

Output: https://www.example.com

Escape text within an HTML attribute

Prevent HTML injection within an attribute value.

$title = 'This is a "title" with quotes';
$safe_title = esc_html( $title );
echo "<a href='#' title='{$safe_title}'>Link</a>";

Output: <a href=’#’ title=’This is a “title” with quotes’>Link</a>

Escape a translation string

Safely escape a translated string for output in HTML.

$translated_text = __( 'Hello <strong>World</strong>', 'text-domain' );
$safe_text = esc_html( $translated_text );
echo $safe_text;

Output: Hello <strong>World</strong>