I want to know what is the difference between these functions.

esc_attr__() and esc_attr_e()

What would be an example of use, when they are recommened to use them.

up vote 5 down vote accepted

The difference is in their source code. If you have a look in the source code of esc_attr__() we'll have this-

function esc_attr__( $text, $domain = 'default' ) {
    return esc_attr( translate( $text, $domain ) );
}

And if we go for the source code of esc_attr_e we'll get this below code block-

function esc_attr_e( $text, $domain = 'default' ) {
    echo esc_attr( translate( $text, $domain ) );
}

Now you can clearly see the difference. esc_attr__() is returning the value and esc_attr_e is echoing the value.

esc_attr__() Use Case Example:

Now if you just want put the translated value of an attribute to some variable you have to use esc_attr__(). See below example-

$translated_value = esc_attr__( 'Your Text', 'your_text_domain' );
<input title="<?php echo $translated_value ?>" type="submit" value="submit" >

Look we are putting the value to $translated_value variable first and then we are echoing it in input field's title attribute.

esc_attr_e Use Case Example:

Well, if you need to echo the attribute directly after translation then you should use esc_attr_e. Example given below-

<input title="<?php esc_attr_e( 'Read More', 'your_text_domain' ) ?>" type="submit" value="submit" >

Hope this above helps.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.