Get localized string for specific locale Get localized string for specific locale wordpress wordpress

Get localized string for specific locale


Old question I know, but here goes -

Starting with a simple example where you know exactly what locales to load and exactly where the MO files are, you could use the MO loader directly:

<?php$locales = array( 'en_US', 'es_ES' );foreach( $locales as $tmp_locale ){    $mo = new MO;    $mofile = get_template_directory().'/languages/'.$tmp_locale.'.mo';    $mo->import_from_file( $mofile );    // get what you need directly    $translation = $mo->translate('Introduction');}

This assumes your MO files are all under the theme. If you wanted to put more of this logic through the WordPress's environment you could, but it's a bit nasty. Example:

<?phpglobal $locale;// pull list of installed language codes$locales = get_available_languages();$locales[] = 'en_US';// we need to know the Text Domain and path of what we're translating$domain = 'my_domain';$mopath = get_template_directory() . '/languages';// iterate over locales, finally restoring the original en_USforeach( $locales as $switch_locale ){    // hack the global locale variable (better to use a filter though)    $locale = $switch_locale;    // critical to unload domain before loading another    unload_textdomain( $domain );    // call the domain loader - here using the specific theme utility    load_theme_textdomain( $domain, $mopath );    // Use translation functions as normal    $translation = __('Introduction', $domain );}

This method is nastier because it hacks globals and requires restoring your original locale afterwards, but it has the advantage of using WordPress's internal logic for loading your theme's translations. That would be useful if they were in different locations, or if their locations were subject to filters.

I also used get_available_languages in this example, but note that you'll need the core language packs to be installed for this. It won't pick up Spanish in your theme unless you've also installed the core Spanish files.