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?
1 Answer
My problem here is that
get_query_var('language')
isn’t defined in the functionset_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/