php – How to pass a variable into an add_filter() function?


I have this code here:

$updatedLanguage = "de";
add_filter('locale', 'change_my_locale');
function change_my_locale( $locale ) {
  $locale = $updatedLanguage;
  return $locale;

I would like to know how to pass the variable $updatedLanguage into the change_my_locale() function please?

in progress 0
Platoscave 1 year 2021-09-03T20:26:33-05:00 0 Answer 0 views 0

Answer ( 1 )


    You could use an anonymous function and pass the variable to it with use.

    $updatedLanguage = $languageArray[$pageLanguage] ?? '';
    if ( $updatedLanguage ) {
        add_filter('locale', function($locale) use ($updatedLanguage) {
            return $updatedLanguage;

    If you’re changing the locale at runtime, then you may want to look here Change locale manually at runtime?, where it is noted that the change could have a performance impact. Also, you may need to do the change early enough in the WP loading sequence so that the correct translation file gets loaded – if it something that you need.

Leave an answer