0

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.

1

2 Answers 2

1

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

1
  • Thanks! I also tried changing the global $locale variable. It worked too! Commented Mar 15, 2017 at 11:50
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.