I'm trying to achieve, that when someone visits my wordpress page the .po (language-) packages of his pefered language are loaded. At the moment it is possible to change the language by adding a ?lang= parameter to the URL. But i want the right language to be selected based on the browser language.
My code:
<?php
// start the session
session_start();
$browserlang = " ".$_SERVER['HTTP_ACCEPT_LANGUAGE'];
// if there's a "lang" parameter in the URL...
if( isset( $_GET[ 'lang' ] ) ) {
// ...set a session variable named WPLANG based on the URL parameter...
$_SESSION[ 'WPLANG' ] = $_GET[ 'lang' ];
// ...and define the WPLANG constant with the WPLANG session variable
$locale = $_SESSION[ 'WPLANG' ];
echo 'Based on URL parameter';
// if there isn't a "lang" parameter in the URL...
} else {
// if the WPLANG session variable is already set...
if( isset( $_SESSION[ 'WPLANG' ] ) ) {
// ...define the WPLANG constant with the WPLANG session variable
$locale = $_SESSION[ 'WPLANG' ];
echo 'Based on session variable';
// if the WPLANG session variable isn't set...
} else {
// set the WPLANG constant to your default language code is (or empty, if you don't need it)
$locale = $browserlang;
echo 'Should be based on browser language. It is:' . $browserlang;
}
};
?>
$locale is used to set the language and select the right .po files.
Now i want $locale to be
$locale = 'en_US'
by default, but when someone enters the page that has default language "de", "de_DE", "de_CH" or "de_AT" it should be.
$locale = 'de_DE'
The Code im currently using isnt working.
$browserlang = " ".$_SERVER['HTTP_ACCEPT_LANGUAGE'];
echo $browserlang;
Shows me the right language, which is "de_DE", but $locale = $browserlang
doesnt do anything. On the other hand when i set $locale = 'de_DE'
it works...
Thank you guys in advance.
Edit:
When i use echo $locale
is says de-DE. Thats very stange, because it doesnt work...
Edit 2:
Thats because it must be de_DE (underline) not de-DE (minus)... how to fix that?
Edit 3:
Finally it works.
Shows me the right language, which is "de_DE",
It shouldn't. The code you've shown us inserts a space before the header value.
Also, your code does not handle a multi-valued accept-language header which can also include preferences (e.g. see here for a parser)
How you normalize the value ( {"de", "de_DE", "de_CH","de_AT"} -> "de_DE" ) is up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With