Using WordPress ‘esc_html_x()’ PHP function

The esc_html_x() WordPress PHP function translates a string with a given context and escapes it for safe use in HTML output. If there’s no translation or if the text domain isn’t loaded, the original text is escaped and returned.

Usage

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

$translated_string = esc_html_x('String to translate', 'Context for translators', 'text-domain');

In this example, 'String to translate' is the text to translate, 'Context for translators' provides context to the translators, and 'text-domain' is the unique identifier for retrieving translated strings.

Parameters

  • $text (string) – Required. The text to translate.
  • $context (string) – Required. Context information for the translators.
  • $domain (string) – Optional. Text domain. Unique identifier for retrieving translated strings. Default is ‘default’.

More information

See WordPress Developer Resources: esc_html_x()

esc_html_x() is similar to the _x() function but also ensures the string is safe for HTML output.

Examples

Example 1

Use esc_html_x() to translate a string within a specific context. Here, the string ‘Comment’ is used as a verb:

<a href="#comment">
  <?php echo esc_html_x('Comment', 'Verb: To leave a comment', 'wpdocs_my_theme'); ?>
</a>

Example 2

In this example, the string ‘Comment’ is used as a noun:

<h3>
  <?php echo esc_html_x('Comment', 'Noun: An individual comment', 'wpdocs_my_theme'); ?>
</h3>

Example 3

Here, we’re translating a string ‘Edit’ in the context of ‘post type singular name’:

<?php echo esc_html_x('Edit', 'post type singular name', 'wpdocs_my_theme'); ?>

Example 4

In this case, we’re translating ‘Archive’ in the context of ‘post type general name’:

<?php echo esc_html_x('Archive', 'post type general name', 'wpdocs_my_theme'); ?>

Example 5

Here, ‘View’ is being translated in the context of ‘verb’:

<?php echo esc_html_x('View', 'verb', 'wpdocs_my_theme'); ?>

Remember, the function esc_html_x() is used to escape the translated string for safe use in HTML output.