Using WordPress ‘is_locale_switched()’ PHP function

The is_locale_switched() WordPress PHP function checks if the locale has been switched using switch_to_locale().

Usage

$locale_switched = is_locale_switched();

Parameters

  • None

More information

See WordPress Developer Resources: is_locale_switched()

Examples

Check if the locale is switched

This code checks if the locale is currently switched and outputs a message accordingly.

if (is_locale_switched()) {
    echo "The locale has been switched!";
} else {
    echo "The locale has not been switched.";
}

Switch locale and check if it’s switched

This code switches the locale to French and then checks if the locale has been switched.

switch_to_locale('fr_FR');
$locale_switched = is_locale_switched();

if ($locale_switched) {
    echo "Bonjour! The locale has been switched to French.";
}

Change locale based on user preference

This code checks if a user has a preferred language set and switches the locale accordingly.

$user_locale = get_user_meta($user_id, 'preferred_locale', true);

if ($user_locale) {
    switch_to_locale($user_locale);
}

if (is_locale_switched()) {
    echo "Locale has been switched to the user's preference.";
}

Switch locale for a specific part of the website

This code switches the locale for a specific part of the website (e.g., a language learning section) and then restores the original locale afterward.

$original_locale = get_locale();
switch_to_locale('es_ES');

if (is_locale_switched()) {
    echo "Bienvenido! The locale has been switched to Spanish for this section.";
}

// Do stuff in Spanish locale here

restore_previous_locale();

Switching locales in a loop

This code demonstrates how to switch between multiple locales in a loop.

$locales = ['fr_FR', 'de_DE', 'es_ES'];

foreach ($locales as $locale) {
    switch_to_locale($locale);

    if (is_locale_switched()) {
        echo "The locale has been switched to " . $locale . ".<br>";
    }

    restore_previous_locale();
}