Setting Wordpress language programmatically?
I came up with following solution as I needed to generate invoices from a plugin in different languages in the scope of the same request:
global $locale;
$locale = 'en_CA';
load_plugin_textdomain('invoice', false, 'my-plugin/languages/');
generateInvoice(); // produce the English localized invoice
$locale = 'fr_CA';
load_plugin_textdomain('invoice', false, 'my-plugin/languages/');
generateInvoice(); // produce the French localized invoice
I found a different solution:
// Set user selected language by loading the lang.mo file
if ( is_user_logged_in() ) {
// add local filter
add_filter('locale', 'language');
function language($locale) {
/* Note: user_meta and user_info are two functions made by me,
user_info will grab the current user ID and use it for
grabbing user_meta */
// grab user_meta "lang" value
$lang = user_meta(user_info('ID', false), 'lang', false);
// if user_meta lang is not empty
if ( !empty($lang) ) {
$locale = $lang; /* set locale to lang */
}
return $locale;
}
// load textdomain and .mo file if "lang" is set
load_theme_textdomain('theme-domain', TEMPLATEPATH . '/lang');
}
Via: http://codex.wordpress.org/Function_Reference/load_theme_textdomain
I guess you're looking for the override_load_textdomain
filter, called just in the beginning of a load_textdomain
function call.
That would be something like:
function my_load_textdomain ($retval, $domain, $mofile) {
if ($domain != 'theme_domain')
return false;
$user = get_currentuserinfo()
$user_lang = get_user_lang($user);
if ($new_mofile = get_my_mofile($user_lang)) {
load_textdomain('theme_domain', $new_mofile);
return true;
}
return false;
}
add_filter('override_load_textdomain', 'my_load_textdomain');
Code from brain to keyboard, not tested. You should do some more validations and so.
Since WP 4.7 you can use:
switch_to_locale('en_US');
Reference: https://developer.wordpress.org/reference/functions/switch_to_locale/