switch_to_locale()
Allows you to programmatically switch the site's language.
One of several functions introduced in WP 4.7 for managing the site's translation for individual users.
The function will work only if the user has set any translation language in their profile settings (any, even "site language").
Use is_locale_switched() to check if the locale is currently switched.
Hooks when switching locale:
Several actions are triggered when switching the locale:
-
change_locale - triggered when the locale has already been changed. The core uses it to re-create post types and taxonomies.
-
switch_locale - triggered when the locale is switched.
- restore_previous_locale - triggered when the locale is returned to the previous one.
No Hooks.
Returns
true|false. True on success, false on failure.
Usage
switch_to_locale( $locale );
- $locale(string) (required)
The name of the locale to switch to. For example:
fr_FRoren_AU.A complete list of locales can be found here
Examples
#1 Switch website language on the fly
Suppose our site is running in Russian, but we need English in the admin panel. Then insert this code in functions.php of the theme:
if( is_admin() ){
switch_to_locale( 'en_US' );
}
You can do it with a hook:
add_action( 'init', function(){
switch_to_locale( 'en_US' );
} ); #2 Set the language of the admin area by condition
Let's assume that we determine the user's locale by IP and put that data into the user_locale cookie. So we know which country the user is from and can set the language of the site on the fly:
add_action( 'init', function(){
if( isset( $_COOKIE['user_locale'] ) ){
switch_to_locale( $_COOKIE['user_locale'] );
}
}
Notes
- Global. WP_Locale_Switcher. $wp_locale_switcher WordPress locale switcher object.
Changelog
| Since 4.7.0 | Introduced. |
switch_to_locale() switch to locale code WP 6.9
function switch_to_locale( $locale ) {
/* @var WP_Locale_Switcher $wp_locale_switcher */
global $wp_locale_switcher;
if ( ! $wp_locale_switcher ) {
return false;
}
return $wp_locale_switcher->switch_to_locale( $locale );
}