Get localized string for specific locale

admin

Administrator
Staff member
How can I use the localization mechanism in WordPress to get access to an existing but not-current language string?

Background: I have a custom theme where I use locale 'en_US' as the default locale and translate through a PO file to locale 'es_ES' (Spanish).

Let us say I use the construction

Code:
__('Introduction', 'my_domain');

in my code, and that I have translated 'Introduction' to the Spanish 'Introducción´ in my PO file. All this works fine.

Now to the problem: I want to insert n records in my database with all existing translations of the string 'Introduction' - one for each language; so, n = 2 in my example.

Ideally, I would write something like this:

Code:
$site_id = 123;
// Get an array of all defined locales: ['en_US', 'es_ES']
$locales = util::get_all_locales();
// Add one new record in table details for each locale with the translated target string
foreach ($locales as $locale) {
    db::insert_details($site_id, 'intro',
        __('Introduction', 'my_domain', $locale), $locale);
}

<strong>Only, that the 3rd parameter in __() above is pure fantasy on my part</strong>. You can only validly write

__('Introduction', 'my_domain');

to get either 'Introduction' or 'Introducción' depending on the current locale.

The outcome of the code above would ideally be that I end up with two records in my table:

Code:
SITE_ID  CAT    TEXT             LOCALE
123      intro  Introduction     en_US
123      intro  Introducción     es_ES

<hr>

I am aware that I want something that requires loading all the MO files, where normally, only the MO file for the current language is required. Maybe use of the WordPress function load_textdomain is necessary - I was just hoping there already exists a solution.

<hr>

Expanding on the question by including the plugin PolyLang: is it possible to use <a href="http://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/" rel="nofollow">Custom Strings</a> to achieve the above functionality? E.g. conceptually:

Code:
pll_('Introduction', $locale)