switch_to_locale()
Allows you to switch the site language programmatically.
This is one of several features introduced in WP 4.7 to control site translation for an individual user.
This function will only work if the user has set any translation language in the profile settings. Or if the user is registered with WP version 4.7 or higher. But if you updated the site version and the user has not yet selected a translation language, the locale will not be switched. This may be fixed in the future.
To check if your locale is currently switched, use is_locale_switched().
Hooks when switching a locale:
When switching a locale, several events are triggered:
-
change_locale - triggers when the locale has already been changed. The core uses it to re-create post types and taxonomies with proper language.
-
switch_locale - triggers when locale is switched.
- restore_previous_locale - triggers when the locale is switched back to the previous one.
No Hooks.
Return
true|false
. True on success, false on failure.
Usage
switch_to_locale( $locale );
- $locale(string) (required)
Name of the locale to switch to. For example:
fr_FR
oren_AU
.See full list of locales.
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.7.1
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 ); }