Using WordPress ‘plugin_locale’ PHP filter

The plugin_locale filter allows you to modify a plugin’s locale, which can be useful for adjusting language settings or translations.

Usage

add_filter('plugin_locale', 'my_custom_plugin_locale', 10, 2);

function my_custom_plugin_locale($locale, $domain) {
  // Your custom code here
  return $locale;
}

Parameters

  • $locale (string) – The plugin’s current locale.
  • $domain (string) – Text domain, a unique identifier for retrieving translated strings.

Examples

Change a plugin’s locale

add_filter('plugin_locale', 'change_my_plugin_locale', 10, 2);

function change_my_plugin_locale($locale, $domain) {
  if ($domain === 'my-plugin') {
    $locale = 'fr_FR';
  }
  return $locale;
}

This code snippet changes the locale of a plugin with the text domain ‘my-plugin’ to French (‘fr_FR’).

Set the plugin’s locale based on the user’s preference

add_filter('plugin_locale', 'user_preference_plugin_locale', 10, 2);

function user_preference_plugin_locale($locale, $domain) {
  if ($domain === 'my-plugin') {
    $user_locale = get_user_meta(get_current_user_id(), 'preferred_locale', true);
    if ($user_locale) {
      $locale = $user_locale;
    }
  }
  return $locale;
}

This example retrieves the user’s preferred locale from their user metadata and sets the plugin’s locale accordingly.

Change the plugin’s locale for admin users only

add_filter('plugin_locale', 'admin_plugin_locale', 10, 2);

function admin_plugin_locale($locale, $domain) {
  if ($domain === 'my-plugin' && current_user_can('manage_options')) {
    $locale = 'de_DE';
  }
  return $locale;
}

This code sets the locale of a plugin with the text domain ‘my-plugin’ to German (‘de_DE’) for users with the ‘manage_options’ capability, typically administrators.

Change the plugin’s locale based on a custom function

add_filter('plugin_locale', 'custom_function_plugin_locale', 10, 2);

function custom_function_plugin_locale($locale, $domain) {
  if ($domain === 'my-plugin' && my_custom_function()) {
    $locale = 'es_ES';
  }
  return $locale;
}

function my_custom_function() {
  // Return true if you want to change the plugin's locale
  return true;
}

This example changes the plugin’s locale to Spanish (‘es_ES’) if the custom function my_custom_function() returns true.

Change the plugin’s locale dynamically based on a query parameter

add_filter('plugin_locale', 'query_param_plugin_locale', 10, 2);

function query_param_plugin_locale($locale, $domain) {
  if ($domain === 'my-plugin' && isset($_GET['locale'])) {
    $locale = sanitize_text_field($_GET['locale']);
  }
  return $locale;
}

In this example, the plugin’s locale is changed based on the value of the ‘locale’ query parameter in the URL. The value is sanitized using sanitize_text_field() to prevent potential security issues.