Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch language in WordPress "on-the-fly"

Is there a way like switch_to_blog() for switching the language in WordPress.

Something like

global $locale
$currentLanguage = $locale;
switch_to_language('de_DE');

//do some action with german localisation

switch_to_language($currentLanguage);

Is this possible in general with WordPress?

like image 548
Xaver Avatar asked Jun 21 '13 07:06

Xaver


1 Answers

So I finally found the solution. The function is called load_textdomain()

This is how it's done on my side. Keep in mind to define LANGUAGE_PATH and the language you would like to switch to in $new_language. $your_domain is the text domain of your plugin/theme

//will output "Good Morning"
_e('Good Morning', $your_domain);

global $locale;
//save the current language for later
$current_language = $locale;
$new_language = 'DE_de';

//load the new text domain
load_textdomain( $your_language_domain, LANGUAGE_PATH.'/'.$your_domain.'-'.$new_language.'.mo' );

//do some action with the new localisation
//will output "Guten Morgen"
_e('Good Morning', $your_domain);

//go back to the previous language
load_textdomain( $your_language_domain , LANGUAGE_PATH.'/'.$your_domain.'-'.$current_language.'.mo' );

Took a while to find this method in the core. Read more about that function on the codex site

like image 76
Xaver Avatar answered Oct 15 '22 09:10

Xaver