Using WordPress ‘esc_attr_x()’ PHP function

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

Usage

Here’s a general usage example:

echo '<div title="' . esc_attr_x( 'Hello, World!', 'welcome text', 'myplugin' ) . '">';

In this example, “Hello, World!” is the text to translate, “welcome text” provides context for the translators, and “myplugin” is the text domain.

Parameters

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

More information

See WordPress Developer Resources: esc_attr_x()

Examples

Translating and escaping a simple string

We’re translating and escaping a simple string “Hello, World!” within the context of ‘welcome text’ in the text domain ‘myplugin’.

echo '<div title="' . esc_attr_x( 'Hello, World!', 'welcome text', 'myplugin' ) . '">';

Translating and escaping a string with special characters

We’re translating and escaping a string “Hi & Welcome!” within the context of ‘greeting text’ in the default text domain. Here, esc_attr_x ensures that the special character “&” is properly escaped.

echo '<div title="' . esc_attr_x( 'Hi & Welcome!', 'greeting text' ) . '">';

Translating and escaping a string in a different text domain

In this example, we’re translating and escaping a string “Good Morning!” within the context of ‘morning greeting’ in the text domain ‘mytheme’.

echo '<div title="' . esc_attr_x( 'Good Morning!', 'morning greeting', 'mytheme' ) . '">';

Using esc_attr_x in form attributes

Here, we’re translating and escaping a string “Search” within the context of ‘placeholder text’ in the text domain ‘myplugin’. This ensures that the placeholder text for our search form is properly translated and escaped.

echo '<input type="text" placeholder="' . esc_attr_x( 'Search', 'placeholder text', 'myplugin' ) . '">';

Translating and escaping a string with no text domain specified

In this case, we’re translating and escaping a string “Submit” within the context of ‘button text’. Since no text domain is specified, the default text domain is used.

echo '<button type="submit">' . esc_attr_x( 'Submit', 'button text' ) . '</button>';