Is this a correct usage of esc_html_e?

<h1 class="page-title"><?php esc_html_e( 'Oops! Something went wrong.', '_amnth' ); ?></h1>

I think this should simply use the __() function, since it’s a static string and it cannot be dynamic and in contrast, HTML.

At the same time, here’s some source code from WooCommerce itself:

<th class="product-name"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th>

So, is it whenever you output a string, dynamic or not, to HTML, you should also escape it with esc_html and so, even if it’s just a string being output, you should use esc_html_e?

Please assume extremely strict escaping rules, where everything needs to be escaped in the right way. (Even so, using esc_html_e seems overkill to the power of 10 ).

3 Answers
3

You should always escape output. end of sentence, and end of story.

The questions is like asking if you can use globals and goto. Sure they are part of the language and in some edge cases they are the only way to produce working and readable code, but the guide is to never use them unless you can prove you have too.

Going down from the theoretical to the practical, it is not true that __ is static string, as if it was static you would not have used it at all, and just used the literal string instead. It is even worse, as the function is meant to supply an easy way to override a string to any other string, a string you might have no idea about its content.

The only place where escaping might result in a bad result on the front end is when someone tries to add html tags to the string as part of the translation, but this is extremely rare case, especially if you had the translators in mind while creating code that does the output.

Following the discussion in the comments, I feel like maybe I should state the reasoning in a different way. Translations should be treated as user input, since users can actually edit them, or use plugin to change them. And all user inputs should be suspect, if not for security reasons than for broken html reasons, and therefor it should be validated, sanitized and escaped.

With a more traditional user input you sometimes can avoid escaping by doing a more rigorous validation and sanitation, but you have no chance of doing that with regard to translation, and escaping is your almost only tool to be able to protect against security holes, and broken html.

Leave a Comment