I was wandering… All the translation functions (__(), _e(), _x()
and so on) use the current/active language. Is there a way to get a translation from another language than the current one? For example, I’m on a French page and I want and english translation: how to?
2 s
To find the answer to this question, you just need to look at how WordPress retrieves the translations. Ultimately it is the load_textdomain()
function that does this. When we take a look at its source we find that it creates a MO
object and loads the translations from a .mo
file into it. Then it stores that object in a global variable called $l10n
, which is an array keyed by textdomain.
To load a different locale for a particular domain, we just need to call load_textdomain()
with the path to the .mo
file for that locale:
$textdomain = 'your-textdomain';
// First, back up the default locale, so that we don't have to reload it.
global $l10n;
$backup = $l10n[ $textdomain ];
// Now load the .mo file for the locale that we want.
$locale="en_US";
$mo_file = $textdomain . '-' . $locale . '.mo';
load_textdomain( $textdomain, $mo_file );
// Translate to our heart's content!
_e( 'Hello World!', $textdomain );
// When we are done, restore the translations for the default locale.
$l10n[ $textdomain ] = $backup;
To find out what logic WordPress uses to determine where to look for the .mo
file for a plugin (like how to get the current locale), take a look at the source of load_plugin_textdomain()
.