[wp-hackers] Multilanguage: how to redefine locale on the fly

Andrew Nacin wp at andrewnacin.com
Fri Mar 8 16:07:51 UTC 2013


On Fri, Mar 8, 2013 at 11:03 AM, Manuel Schmalstieg <webdev at ms-studio.net>wrote:

> Update: I'm now inclined to use a workaround based on the post slug.
> This makes the language switch as simple as this:
>
> function wpsx89972_redefine_locale($locale) {
>     $wpsx_url = $_SERVER['REQUEST_URI'];
>     $wpsx_url_lang = substr($wpsx_url, -4);
>     if ( $wpsx_url_lang == "-fr/") {
>         $locale = 'fr_FR';
>     } else if ( $wpsx_url_lang == "-en/") {
>         $locale = 'en_US';
>     } else { // fallback to default
>         $locale = 'de_DE';
>     }
>     return $locale;
> }
> add_filter('locale','wpsx89972_redefine_locale',10);
>
> Still a bit disappointed as I would prefer a fully taxonomy-based
> method... but at least I now have a working multi-language solution in
> 13 lines of code, not that bad \o/
>

Since you're just switching from English to one other language, you can
consider filtering 'locale' once the post is loaded (on template_redirect).

The key is to re-load the default textdomain after filtering 'locale'.

add_filter( 'template_redirect', function() {
    add_filter( 'locale', ... );
    load_default_textdomain();
});

This won't quite result in every string translated, as some will be
translated before template_redirect, but you are unlikely to notice on the
frontend.

Nacin


More information about the wp-hackers mailing list