How to change language file used by _e function

I am trying to make my own language switcher for my WordPress site. I am generating all labels using the _e and similar functions. So I am guessing the only thing I need to do is to change the locale used by WordPress. How can I do this programmatically?

So in the ideal scenario when a user clicks on the desired language "this code" is run and WordPress uses the corresponding .mo file for the translation.

Topic language multi-language Wordpress

Category Web


In addition to @maxime's answer, I found that the following method worked too. Simply change the $locale global variable. This will fix most translations. If you want to specify the locale for specific text domains, then simply call the load_textdomain() function pointing to the appropriate .mo file.

$locale = 'en_US';

if ( file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {
    load_textdomain( 'my_domain', WP_LANG_DIR . '/' . $locale . '.mo' );
}

Now, in the above example, if your languages folder contains the file en_US.mo, you're good to go.

So when you call something like,

echo _e('Hello', 'my_domain');

the appropriate translations in your associated .po file will be reflected.

You can find a detailed explanation at https://codex.buddypress.org/getting-started/customizing/customizing-labels-messages-and-urls/.

This is intended for BuddyPress, but the idea applies generally.


Actually you need to hook in the 'locale' filter to set the language you want:

add_filter('locale', function($locale) {
    return esc_attr($_GET['language']);
});

Then in the links of your switch, you need to pass the language variable:

<a href="<?php echo add_query_arg('language', 'xx_XX') ?>">XX</a>

Where xx_XX is the language locale code for language XX

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.