How do translated, escaped strings (esc_attr) in Themes work?

General difference between esc_attr and esc_attr_*

The difference between esc_attr() and esc_attr__(), esc_attr_e(), esc_attr_x() is that the later three are just “wrappers” or in other words higher level API functions.

When you look at the source of the later three, then you’ll see that those put in a single argument wrapped in a call to translate() (or translate_with_gettext_context() for esc_attr_x().

That means that you’re just throwing two arguments in: The string to translate and the textdomain that helps WP determining which language file to take for the translation.

Everything else you see is the sprintf() around it, which is default php function that replaces %s-parts and %d-parts in a string (string/digit).

Minetrap! Be aware!

If you’re not passing a second argument to the later three versions of esc_attr(), then you’ll run into the following problem: WP now thinks that your strings are part of core and tries to translate them. Which can lead to very odd results.

Another thing that might happen is that the translation string (the 2nd arg) is already used by a plugin or theme. In this case, the later loaded translation file wins the race and is taken instead of your file. Again: Very odd results. Fix: Prefix your textdomain, as you’d do it with custom globals or function names.

Conclusion

If you want to avoid a second argument, then simply go with esc_attr( 'your string' ) and avoid the other three versions.

Leave a Comment