Xaver
Xaver

Reputation: 11692

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?

Upvotes: 7

Views: 5264

Answers (2)

Xaver
Xaver

Reputation: 11692

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

Upvotes: 15

LucP
LucP

Reputation: 126

I'm afraid you're going to need a plugin for that. WordPress doesn't do that out of the box. WPML is usually the go-to multi-lingual plugin for WordPress, you should check it out :)

Upvotes: 1

Related Questions