The determine_locale WordPress PHP filter allows you to change the locale for the current request.
Usage
add_filter('determine_locale', 'my_custom_locale_function'); function my_custom_locale_function($locale) { // your custom code here return $locale; }
Parameters
$locale
(string) – The locale you want to set for the current request.
More information
See WordPress Developer Resources: determine_locale
Examples
Change the locale to French
This code sets the locale to French (fr_FR) for the current request:
add_filter('determine_locale', 'set_french_locale'); function set_french_locale($locale) { $locale = 'fr_FR'; return $locale; }
Change the locale based on user preference
This code changes the locale based on a user’s preference stored in user meta:
add_filter('determine_locale', 'set_user_preferred_locale'); function set_user_preferred_locale($locale) { if (is_user_logged_in()) { $user_id = get_current_user_id(); $user_locale = get_user_meta($user_id, 'preferred_locale', true); if ($user_locale) { $locale = $user_locale; } } return $locale; }
Change the locale based on a URL parameter
This code changes the locale based on a ‘lang’ URL parameter:
add_filter('determine_locale', 'set_locale_from_url'); function set_locale_from_url($locale) { if (isset($_GET['lang'])) { $locale = sanitize_text_field($_GET['lang']); } return $locale; }
Change the locale based on browser language
This code sets the locale based on the user’s browser language:
add_filter('determine_locale', 'set_locale_from_browser'); function set_locale_from_browser($locale) { $browser_language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); switch ($browser_language) { case 'fr': $locale = 'fr_FR'; break; case 'es': $locale = 'es_ES'; break; // Add more cases for different languages default: break; } return $locale; }
Change the locale for a specific page
This code sets the locale to French (fr_FR) for a specific page with the ID 123:
add_filter('determine_locale', 'set_locale_for_specific_page'); function set_locale_for_specific_page($locale) { if (is_page(123)) { $locale = 'fr_FR'; } return $locale; }