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

admin2025-06-05  2

I was looking at the TwentyEleven code and found this:

esc_attr__( 'Permalink to %s', 'twentyeleven' )

This is some code that came out of the title tag for a post; the full code within the title tag being:

printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) );

I checked out the documentation for the esc_attr function (appears to be the same as the esc_attr__ function?) and it states it only takes one parameter, so how is this passing it two parameters?

I was looking at the TwentyEleven code and found this:

esc_attr__( 'Permalink to %s', 'twentyeleven' )

This is some code that came out of the title tag for a post; the full code within the title tag being:

printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) );

I checked out the documentation for the esc_attr function (appears to be the same as the esc_attr__ function?) and it states it only takes one parameter, so how is this passing it two parameters?

Share Improve this question edited Dec 12, 2018 at 15:59 Brett asked Sep 26, 2012 at 10:30 BrettBrett 4145 silver badges25 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 6

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749105521a316407.html

最新回复(0)