The locale WordPress PHP Filter allows you to modify the locale ID of the WordPress installation.
Usage
add_filter( 'locale', 'my_custom_locale' ); function my_custom_locale( $locale ) { // your custom code here return $locale; }
Parameters
- $locale (string): The locale ID.
More information
See WordPress Developer Resources: locale
Examples
Change Locale to Spanish
This code changes the locale ID to Spanish (es_ES).
add_filter( 'locale', 'change_locale_to_spanish' ); function change_locale_to_spanish( $locale ) { return 'es_ES'; }
Set Locale Based on User’s Preference
This code sets the locale based on the user’s preference stored in the user meta.
add_filter( 'locale', 'set_locale_based_on_user_preference' ); function set_locale_based_on_user_preference( $locale ) { if ( is_user_logged_in() ) { $user_id = get_current_user_id(); $preferred_locale = get_user_meta( $user_id, 'preferred_locale', true ); if ( $preferred_locale ) { return $preferred_locale; } } return $locale; }
Change Locale for Admin Area
This code changes the locale ID for the admin area to French (fr_FR).
add_filter( 'locale', 'change_locale_for_admin_area' ); function change_locale_for_admin_area( $locale ) { if ( is_admin() ) { return 'fr_FR'; } return $locale; }
Change Locale Based on URL Parameter
This code changes the locale based on the URL parameter lang
.
add_filter( 'locale', 'change_locale_based_on_url_parameter' ); function change_locale_based_on_url_parameter( $locale ) { if ( isset( $_GET['lang'] ) ) { return sanitize_text_field( $_GET['lang'] ); } return $locale; }
Reset Locale to Default
This code resets the locale to the default WordPress installation locale.
add_filter( 'locale', 'reset_locale_to_default', 100 ); function reset_locale_to_default( $locale ) { return 'en_US'; }