When writing a WordPress plugin recently, I wasn’t sure whether a translatable text/string is considered safe, or if it needs to escaped before being output.
Here’s a simple example:
The Problem
At first glance, that code looks like it should be safe, however what would happen if the string was translated to contained an angled bracket (<
or >
)?
That would result in invalid HTML code. Or even worse, what if the translation file contained a malicious <script>
tag?
The Solution
After some searching through the WordPress source code, I came across the esc_html__()
function:
esc_html__(): Retrieves the translation of $text and escapes it for safe use in HTML output. If there is no translation, or the domain isn’t loaded, the original text is returned.
So in order to make the above example safe/secure, it should be written as:
(There is also the corresponding esc_html_e() function, which is used if you want to output the text automatically without having to echo
it).
Another Example
Another example is if the translatable string is going to be used inside a HTML attribute:
You would use the esc_attr__()
function:
esc_attr__(): Retrieves the translation of $text and escapes it for safe use in an attribute. If there is no translation, or the domain isn’t loaded the original text is returned.
So in order to make the above example safe/secure, it should be written as:
(There is also the corresponding esc_attr_e() function, which is used if you want to output the text automatically without having to echo
it).
For more information see the WordPress Codex article on Data Validation.
Conclusion
So it seems that the “Trust No One” philosophy when retrieving or outputting data not only applies to end-users, but also to translators and translation files!
Is the above advice is correct? Or do you think it’s unnecessary to escape translatable strings?
Please let me know in the comments.
2 replies on “Should I escape translated strings in a WordPress plugin or theme?”
[…] Post navigation ← Previous […]
Coming across this same question myself. Here’s a good thread for you to check: https://github.com/Automattic/_s/issues/231