Using WordPress ‘get_user_locale()’ PHP function

The get_user_locale() WordPress PHP function retrieves the locale of a user.

Usage

$locale = get_user_locale($user);

Example:

$user_id = 1;
$locale = get_user_locale($user_id);
echo $locale; // Output: 'en_US'

Parameters

  • $user (int|WP_User) – User’s ID or a WP_User object. Defaults to current user.

More information

See WordPress Developer Resources: get_user_locale()

Examples

Get locale of current user

This example retrieves the locale of the currently logged-in user.

$current_user_locale = get_user_locale();
echo "Current user locale: " . $current_user_locale;

Get locale of a specific user by ID

This example retrieves the locale of a user with a specific user ID.

$user_id = 2;
$specific_user_locale = get_user_locale($user_id);
echo "User ID {$user_id} locale: " . $specific_user_locale;

Get locale of a specific user by WP_User object

This example retrieves the locale of a user using a WP_User object.

$user_id = 3;
$user_object = get_user_by('id', $user_id);
$user_locale = get_user_locale($user_object);
echo "User ID {$user_id} locale: " . $user_locale;

Display a message in the user’s locale

This example displays a message based on the user’s locale.

$current_user_locale = get_user_locale();

if ($current_user_locale === 'en_US') {
    echo "Hello!";
} elseif ($current_user_locale === 'es_ES') {
    echo "¡Hola!";
} else {
    echo "Greetings!";
}

Get all users’ locales

This example retrieves the locales of all users on the site.

$all_users = get_users();

foreach ($all_users as $user) {
    $user_locale = get_user_locale($user);
    echo "User ID {$user->ID} locale: " . $user_locale . "<br>";
}