Using WordPress ‘change_locale’ PHP action

The change_locale WordPress PHP action fires when the locale is switched to or restored.

Usage

add_action('change_locale', 'my_custom_function');
function my_custom_function($locale) {
    // your custom code here
}

Parameters

  • $locale (string) – The new locale.

More information

See WordPress Developer Resources: change_locale

Examples

Display a message when the locale is changed

In this example, a message is displayed when the locale is changed.

add_action('change_locale', 'display_locale_change_message');
function display_locale_change_message($locale) {
    echo 'The locale has been changed to: ' . $locale;
}

Update a custom language option

In this example, a custom language option is updated whenever the locale changes.

add_action('change_locale', 'update_custom_language_option');
function update_custom_language_option($locale) {
    update_option('my_custom_language', $locale);
}

Log the locale change

In this example, the locale change is logged to a custom log file.

add_action('change_locale', 'log_locale_change');
function log_locale_change($locale) {
    error_log('Locale changed to: ' . $locale, 3, '/path/to/custom.log');
}

Send an email when the locale is changed

In this example, an email is sent to the site administrator when the locale is changed.

add_action('change_locale', 'send_email_on_locale_change');
function send_email_on_locale_change($locale) {
    $to = get_option('admin_email');
    $subject = 'Locale changed on ' . get_bloginfo('name');
    $message = 'The locale has been changed to: ' . $locale;

    wp_mail($to, $subject, $message);
}

Change the date format based on the locale

In this example, the date format is updated based on the new locale.

add_action('change_locale', 'update_date_format_based_on_locale');
function update_date_format_based_on_locale($locale) {
    if ($locale == 'en_US') {
        update_option('date_format', 'F j, Y');
    } elseif ($locale == 'de_DE') {
        update_option('date_format', 'j. F Y');
    }
}