How to switch locale per page request (also in AJAX)

Locale in Wordpress is defined by constant `WP_LANG` which is, by nature of constants, unchangable during page request. How to deal with that?

 

Spoiler alert: As always with WordPress, it’s all about the hooks.

You can actually overwrite WP_LANG constant from a filter. Cool thing is that this filter runs pretty much everywhere, be it WP’s back-end, theme code or AJAX requests.

If you’re able to guess your current language version from some global state, such as your current page URL, just do it from the filter and return current locale.

Not all of the code has access to global states. AJAX calls are, for example, basically calls to an admin url – so in those cases, you need to pass locale manually.

add_filter('locale', function($locale) {

if (!is_admin()) {
    // you have to write this function by yourself
    $locale = get_locale_from_current_url();
} elseif ((defined('DOING_AJAX') && DOING_AJAX)) {
    // pass locale to an ajax call
    $locale = $_POST['locale']; 
}

return $locale;

});

Any l18n texts (those pesky __() functions) will now return content from language you’ve returned from the filter. Cool, right?

Thank you!
Just a second.

My blog

Categories
Tags
Listening

Getting the tracks.

Just a second.