When to Use __() and Esc_Html_E?

Can anyone explain why I would use __() over esc_html_e()?

4 Answers

__() is primarily for simple text that doesn't contain markup that needs to be escaped. It differs from _e() in that the former returns the translated text while the latter echoes the translated text.

esc_html_e() and esc_html__() are similar, but they are used for strings that do contain markup. They each escape the provided string, and then call on their corresponding _e() or __() counterparts depending on which one you use.

Escaping HTML is necessary if you're accepting strings provided from user input. XSS attacks are probably the most common types of attacks on sites that accept user input and render it on the page. An attacker can easily provide <script> tags and execute arbitrary Javascript on your page if the input is not properly cleaned or escaped.

Just like the docs state, esc_html_e() retrieves a translated string, escapes it, and echoes the result. __() returns a translated string. The source for each of these functions makes this crystal clear:

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

function esc_html_e( $text, $domain = 'default' ) {
    echo esc_html( translate( $text, $domain ) );
}

As for the purpose of esc_html_e(), as I understand it, is to prevent weird characters from translated strings (not the original ones you see in the code).

But _e() is just for translating, without any escape.

It is simple Devs. If you want to echoes or print the translated string,you can use esc_html_e & if you don't want to print that translated string & only want to return its value, you can use __().

You can take reference from esc_html_e & __() for more info.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest