I'm developing a multilangual theme. I use the __() function for translation, which works just fine. The main language is English, but the second language is German. For that second language, I'd like to add an "/de/"-Slug, so I created a rewrite rule:

function rewrite_rule_de(){
    add_rewrite_rule('de/(.+?)/?$', 'index.php?pagename=$matches[1]&language=de', 'top');
add_action('init', 'rewrite_rule_de');

As you can see, I also added a get-variable (language=de), which should tell Wordpress, that the page being displayed is German. Because Wordpress doesn't simply process this get-variable, I added it to query_vars:

function language_query_var($public_query_vars){
    $public_query_vars[] = 'language';  
    return $public_query_vars;  
add_action('query_vars', 'language_query_var');

I want to change the locale, based on the language of the page beeing displayed, so I use the following function:

function set_my_locale( $lang ){
  if ('de' == get_query_var('language')){
    return 'de_DE';
    return 'en_US';
add_filter('locale', 'set_my_locale');

My problem here is that get_query_var('language') isn't defined in the function "set_my_locale". But it works when used before the loop, for example...

So my question is simply: How can I change the locale (so that the __()-function outputs the proper language) based on a rewrite-rule?

1 Answer 1


My problem here is that get_query_var('language') isn't defined in the function set_my_locale

Because get_locale (which applies the filter locale) is called before wp() (which parses the query & sets up the variables).

You'll have to manually inspect the request yourself:

if ( strpos( $_SERVER['REQUEST_URI'], '/de/' ) === 0 ) {
    // German
} else {
    // English

Note this expects WordPress to be running under the root URL i.e. http://example.com/

  • A possible work-around for the root issue is split the request URI into an array using explode and then checking if the language is in the array. Of course, this is entirely theoretical so YMMV. Jul 25, 2012 at 2:47
  • I would probably opt to use the logic in WP::parse_request(), since it's a more rigorous check (ensures de isn't simply lingering anywhere in the URI fragment), but since it's an isolated case I chose to KISS ;) Jul 25, 2012 at 4:20
  • Thanks - although this seems a bit non-standardised. Thought there would be a more "wordpress-like" way of doing this...
    – lupor
    Jul 25, 2012 at 13:20

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.