Using WordPress ‘esc_attr__()’ PHP function

The esc_attr__() function in WordPress PHP retrieves the translation of a text and makes it safe to use within an attribute. If there is no translation available or the text domain isn’t loaded, the original text will be returned.

Usage

Here’s a general usage example:

$translated_text = esc_attr__( 'Hello World', 'my-text-domain' );
echo '<div title="' . $translated_text . '">Welcome to our site</div>';

In this example, ‘Hello World’ is the text to be translated, and ‘my-text-domain’ is the unique identifier for retrieving translated strings.

Parameters

  • $text (string, required): The text to be translated.
  • $domain (string, optional): The text domain, which is a unique identifier for retrieving translated strings. The default value is ‘default’.

More information

See WordPress Developer Resources: esc_attr__

This function is a part of WordPress core and is not deprecated as of the latest update. You can find its source code in the wp-includes/l10n.php file in the WordPress codebase.

Examples

Basic Usage

This is a simple usage of esc_attr__(). Here we are translating a simple greeting ‘Hello’ using a text domain named ‘my-text-domain’.

$translated_greeting = esc_attr__( 'Hello', 'my-text-domain' );
echo '<div title="' . $translated_greeting . '">Welcome to our site</div>';

Using Default Text Domain

In this example, we don’t provide a text domain, so the default ‘default’ is used.

$translated_text = esc_attr__( 'Good Morning' );
echo '<div title="' . $translated_text . '">Have a great day</div>';

Using Different Text Domains

Here we use two different text domains for two different texts.

$hello = esc_attr__( 'Hello', 'domain1' );
$world = esc_attr__( 'World', 'domain2' );
echo '<div title="' . $hello . ' ' . $world . '">Hello, World!</div>';

Using Non-Existent Text Domain

If a non-existent text domain is used, the original text is returned.

$translated_text = esc_attr__( 'Hello World', 'non-existent-domain' );
echo '<div title="' . $translated_text . '">Welcome to our site</div>';

Using Translated Text in Button Attribute

This example shows how to use translated text as a button attribute.

$button_text = esc_attr__( 'Click me', 'my-text-domain' );
echo '<button title="' . $button_text . '">Press Here</button>';