Using WordPress ‘determine_locale()’ PHP function

The determine_locale() WordPress PHP function is used to determine the current locale based on the request.

Usage

A basic usage of the determine_locale() function would look like this:

$current_locale = determine_locale();
echo $current_locale;

In the example above, the function determine_locale() is called and its return value (the locale) is stored in the variable $current_locale. This is then output to the browser using echo.

Parameters

  • determine_locale() does not take any parameters.

More information

See WordPress Developer Resources: determine_locale()

This function is included in WordPress since version 5.0.0. It is not deprecated and is widely used in many WordPress themes and plugins for localization.

Examples

Displaying the Current Locale

$current_locale = determine_locale();
echo "The current locale is: " . $current_locale;

In this example, the current locale is determined using the determine_locale() function and then concatenated with a string to give a user-friendly output.

Checking if the Locale is English

$current_locale = determine_locale();
if (strpos($current_locale, 'en_') !== false) {
    echo "You are using English!";
}

This example checks if the current locale is English by checking if the string starts with ‘en_’.

Switching Content Based on Locale

$current_locale = determine_locale();
if ($current_locale == 'fr_FR') {
    echo "Bonjour le monde!";
} else {
    echo "Hello world!";
}

In this example, we display a greeting in French if the locale is French, otherwise we display the greeting in English.

$current_locale = determine_locale();
setcookie("user_locale", $current_locale, time()+3600);

In this example, we set a cookie named “user_locale” with the value of the current locale. The cookie will expire in 1 hour.

Loading a Different Stylesheet Based on Locale

$current_locale = determine_locale();
if ($current_locale == 'ar_AR') {
    wp_enqueue_style('rtl-stylesheet', get_template_directory_uri() . '/rtl.css');
} else {
    wp_enqueue_style('ltr-stylesheet', get_template_directory_uri() . '/style.css');
}

This example enqueues a right-to-left stylesheet if the locale is Arabic, and a left-to-right stylesheet for any other locales.