Using WordPress ‘restore_previous_locale()’ PHP function

The restore_previous_locale() WordPress PHP function restores the translations according to the previous locale.

Usage

restore_previous_locale();

Parameters

  • None

More information

See WordPress Developer Resources: restore_previous_locale()

Examples

Switching between two locales temporarily

You want to display content in two different languages, and you need to switch between locales temporarily.

// Change the locale to French
switch_to_locale('fr_FR');

// Display content in French
_e('Hello, World!', 'your-text-domain');

// Restore the previous locale
restore_previous_locale();

// Display content in the original language
_e('Hello, World!', 'your-text-domain');

Sending a multilingual email

Send an email with content in both English and Spanish.

// Store the English message
$message_en = __('Your order has been received.', 'your-text-domain');

// Switch to Spanish locale
switch_to_locale('es_ES');

// Store the Spanish message
$message_es = __('Su pedido ha sido recibido.', 'your-text-domain');

// Restore the previous locale
restore_previous_locale();

// Combine messages and send the email
$message = $message_en . "\n" . $message_es;
wp_mail($email, $subject, $message);

Generating multilingual sitemap

Create a sitemap with URLs for posts in English and French.

// Query for published posts
$posts_query = new WP_Query(array('post_type' => 'post', 'post_status' => 'publish'));

// Iterate through the posts
while ($posts_query->have_posts()) {
    $posts_query->the_post();

    // Get the English URL
    $url_en = get_permalink();

    // Switch to French locale
    switch_to_locale('fr_FR');

    // Get the French URL
    $url_fr = get_permalink();

    // Restore the previous locale
    restore_previous_locale();

    // Output sitemap entry
    echo "<url><loc>$url_en</loc><loc>$url_fr</loc></url>";
}

Translating user input for display

Display user input in the original language and a second language.

// Store user input
$user_input = 'Hello, World!';

// Display user input in the original language
echo $user_input;

// Translate user input using a custom function
$translated_input = custom_translate_function($user_input, 'fr_FR');

// Switch to French locale
switch_to_locale('fr_FR');

// Display translated input
echo $translated_input;

// Restore the previous locale
restore_previous_locale();

Localizing date and time output

Output the date and time in the original locale and a second locale.

// Store the current date and time
$current_time = current_time('timestamp');

// Display the date and time in the original locale
echo date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $current_time);

// Switch to German locale
switch_to_locale('de_DE');

// Display the date and time in German
echo date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $current_time);

// Restore the previous locale
restore_previous_locale();