0

I have this code here:

$pageLanguage = strtolower($pageMetadata["language"]); 

$languageArray = array ("afrikaans" => "af", "dutch" => "nl", "french" => "fr", "german" => "de", "spanish" => "es"); 

$updatedLanguage = $languageArray[$pageLanguage];

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?

2
  • Can you elaborate on what you’re trying to do? In your example you would just define the variable inside the function. Commented Sep 4, 2021 at 2:45
  • Yes sorry I understand that I could move that variable as it is written into the function. I am getting the value of $updatedLanguage from other code that can't go into the function, I have updated the question with the extra code. Basically, I getting the language of the page from the $pageMetadata array, and then want to update it using the filter. Is this the correct way to approach this?
    – Platoscave
    Commented Sep 4, 2021 at 2:59

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.