Using WordPress ‘esc_html__()’ PHP function

The esc_html__() WordPress PHP function retrieves the translation of a text and escapes it for safe use in HTML output. If there’s no translation, or the text domain isn’t loaded, the original text is escaped and returned.

Usage

Here’s a basic usage of esc_html__() function:

$greeting = esc_html__( 'Welcome to our site!', 'my-text-domain' );
echo '<h1>' . $greeting . '</h1>';

In this example, the function will attempt to translate the string ‘Welcome to our site!’ using ‘my-text-domain’. It will also ensure that the resulting text is safe to use in HTML output.

Parameters

  • $text (string): The text to translate.
  • $domain (string): The text domain. This is a unique identifier for retrieving translated strings. The default value is ‘default’.

More information

See WordPress Developer Resources: esc_html__

It’s important to remember that esc_html__() also allows you to ensure that third-party translations are sanitized and won’t break the code. This is a critical security measure to keep your users safe.

For echoing the string value directly, consider using the related function esc_html_e().

Examples

Basic usage

// Translate and escape a simple greeting message
$greeting = esc_html__( 'Hello, World!', 'my-text-domain' );
echo '<p>' . $greeting . '</p>';

Translate and escape a title in a H1 tag

$title = esc_html__( 'Welcome to our website!', 'my-text-domain' );
echo '<h1>' . $title . '</h1>';

Use within a longer HTML string

$button_text = esc_html__( 'Click here', 'my-text-domain' );
echo '<button>' . $button_text . '</button>';

Translate and escape a form label

$label_text = esc_html__( 'Enter your name', 'my-text-domain' );
echo '<label>' . $label_text . '</label>';

Translate and escape a string with HTML special characters

$special_text = esc_html__( '5 < 10 and 10 > 5', 'my-text-domain' );
echo '<p>' . $special_text . '</p>';

In all these examples, the esc_html__() function is used to translate and escape a string for safe use in HTML output. This ensures that the resulting string won’t cause any issues when included in the HTML of a webpage.