I am trying to ensure that when someone visits my Wordpress page, the .po (language-) packages of his pefered language are loaded. At the moment, you can change the language by adding the parameter? Lang = in URL. But I want the correct language to be selected based on the language of the browser.
My code is:
<?php // start the session session_start(); $browserlang = " ".$_SERVER['HTTP_ACCEPT_LANGUAGE']; // if there 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 correct .po files.
Now I want $ locale to be
$ locale = 'en_US'
by default, but when someone enters the page with the default "de", "de_DE", "de_CH" or "de_AT", it should be.
$ locale = 'de_DE'
The currently used im code does not work.
$browserlang = " ".$_SERVER['HTTP_ACCEPT_LANGUAGE']; echo $browserlang;
Shows me the correct language, which is "de_DE", but $locale = $browserlang does nothing. On the other hand, when I set $locale = 'de_DE' , it works ...
Thanks guys in advance.
Edit:
When I use echo $locale , de-DE says. This is very strange because it does not work ...
Edit 2:
This is because it should be de_DE (underscore) not de-DE (minus) ... how to fix it?
Edit 3:
Finally, it works.
source share