Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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';
  }else{
    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?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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/

share|improve this answer
    
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. –  Joseph Jul 25 '12 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 ;) –  TheDeadMedic Jul 25 '12 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 '12 at 13:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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