Using WordPress ‘esc_html_e()’ PHP function

The esc_html_e() WordPress PHP function displays translated text that has been escaped for safe use in HTML output. If no translation is available, or the text domain isn’t loaded, the original text is safely escaped and displayed.

Usage

Here’s a basic use case for esc_html_e():

esc_html_e('Hello, world!', 'text-domain');

In this example, ‘Hello, world!’ is the text to translate and ‘text-domain’ is the unique identifier for retrieving translated strings.

Parameters

  • $text (string) Required: The text to translate.
  • $domain (string) Optional: 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_e()
The function was implemented in WordPress 2.8.0. It is part of the secure function family, providing secure translation and echo capabilities.

Examples

Basic Usage

This code displays “Hello, world!” in the current language setting of your WordPress site.

esc_html_e('Hello, world!', 'text-domain');

Using a Different Text Domain

Here, ‘my-plugin’ is used as the text domain, which could be useful if you are creating a plugin and need your own set of translations.

esc_html_e('Hello, world!', 'my-plugin');

Using the Default Text Domain

If no text domain is provided, ‘default’ is used.

esc_html_e('Hello, world!');

Displaying a Longer Text

Escaping and translating a longer text.

esc_html_e('This is a much longer text to translate.', 'text-domain');

Displaying Special Characters

Even if the text contains special characters, they will be safely escaped.

esc_html_e('Hello & welcome, world!', 'text-domain');

This will display “Hello & welcome, world!” in the browser, with the ampersand character safely escaped.