When using a WordPress translation function, e.g. __(), you need to use a hardcoded string (not a variable).
Good
echo __( 'My message', 'salcode-example' );
Bad
$msg = 'My message';
echo __( $msg, 'salcode-example' );
Why?
While the two examples above behave in the same manner, the difference occurs when creating a translation file (a process called localization, which is often abbreviated l10n
).
When creating a translation file, the first step is to generate a list of strings to be translated. The gettext program creates the list of strings by searching the source code and identifying translation functions and the strings that appear in them.
The gettext program uses regular expressions, it does not analyze how any of the code runs. If you use a variable instead of a hardcoded string, gettext will be unaware of the string that needs to be translated.
Strings to be translated are identified using regular expressions.
In the following, gettext would fail to identify My message
as a string to be translated because it does not directly appear in the __()
function call.
$msg = 'My message';
echo __( $msg, 'salcode-example' );
Text Domains
The second parameter of __(), the text domain, should be hardcoded as well. The text domain will not be identified by gettext if a variable is used. Mark Jaquith has written more about this in his post Translating WordPress Plugins and Themes: Don’t Get Clever.
Variable Content in Translated Strings
In the case where your string has variable content inside it, you can use placeholders in your strings along with printf. See the WordPress documentation on placeholders when internationalizing your code.
Leave a Reply