WordPress at Your Fingertips

switch_to_locale() WP 4.7.0

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 or en_AU.

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.

Code of switch_to_locale() WP 5.8.1

function switch_to_locale( $locale ) {
	/* @var WP_Locale_Switcher $wp_locale_switcher */
	global $wp_locale_switcher;

	return $wp_locale_switcher->switch_to_locale( $locale );
}

locale (site language)

localize (l10n i18n Internationalization localization)

Localization

No comments
    Log In