The esc_attr_e() WordPress PHP function displays translated text that has been safely escaped for use in an attribute. It encodes characters like <, >, &, “, ‘ (less than, greater than, ampersand, double quote, single quote) to prevent security vulnerabilities. This function will never double encode entities.
Usage
esc_attr_e($text, $domain);
In this example, $text
is the text you want to translate and escape, and $domain
is the unique identifier for retrieving translated strings. If the $domain
is not specified, it defaults to ‘default’.
Parameters
$text
(string) – This is the text you want to translate and escape. This parameter is required.$domain
(string) – This is a unique identifier for retrieving translated strings. This parameter is optional and defaults to ‘default’.
More information
See WordPress Developer Resources: esc_attr_e()
The esc_attr_e() function was implemented in WordPress 2.8.0. It is not deprecated and is actively used for safer handling and presentation of text.
Examples
Using esc_attr_e() in a form field
Let’s say you want to create a submit button and you want the title attribute to be a translated string. You could do it like this:
// In this case 'Read More' is the text to translate and 'your_text_domain' is the text domain echo '<input title="'; esc_attr_e( 'Read More', 'your_text_domain' ); echo '" type="submit" value="submit" />';
Escaping and translating form labels
You might need to use translated strings as labels in your form. This example shows you how:
// 'Email Address' is the text to translate and 'your_text_domain' is the text domain echo '<label>'; esc_attr_e( 'Email Address', 'your_text_domain' ); echo '</label>';
Using esc_attr_e() with default text domain
If you don’t specify a text domain, it defaults to ‘default’:
// 'Submit' is the text to translate echo '<button>'; esc_attr_e( 'Submit' ); echo '</button>';
Escaping and translating text in hyperlink titles
This function can also be useful when adding titles to your hyperlinks:
// 'Click here' is the text to translate and 'your_text_domain' is the text domain echo '<a href="#" title="'; esc_attr_e( 'Click here', 'your_text_domain' ); echo '">Link</a>';
Using esc_attr_e() in a custom function
You can also use this function within your own custom functions to ensure text is escaped and translated:
function custom_function($text, $domain) { echo '<p>'; esc_attr_e( $text, $domain ); echo '</p>'; } // Call the custom function custom_function('Hello, World!', 'your_text_domain');
In this example, ‘Hello, World!’ is the text to translate and ‘your_text_domain’ is the text domain.