I have a user based website with Wordpress and from their profile settings they are able to select the language, this info and other settings are set for every user in user_meta.
I know how to translate but, is there a way to set the theme language programmatically?
Thank you!
Edit: No plugins please, I need to do this as simple as possible.
Since WP 4.7 you can use:
switch_to_locale('en_US');
Reference: https://developer.wordpress.org/reference/functions/switch_to_locale/
For me only these two solutions together worked.
switch_to_locale($locale);
load_textdomain('example_domain', $mo_file_full_path);
                        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 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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With