I'm doing a bit of language detection that first checks the $_SERVER['HTTP_ACCEPT_LANGUAGE']. If the user wants to override the choice of language, there's a select list, where they can choose whatever language they prefer.
SO: I need to check first if the $_POST superglobal contains a value from the select list. If it does I want to set a cookie. If there's no $_POST value set then I check for a cookie and if there's no cookie I'll go ahead and use the $_SERVER['HTTP_ACCEPT_LANGUAGE'] as the default language.
The code looks like this:
function rps_set_language_preferences() {
global $language;
if( isset( $_POST['sprak'] ) ) {
$possible_langs = array( 'en', 'de', 'ko' );
$my_cookie = $_POST['sprak'];
if( in_array( $my_cookie, $possible_langs ) ) {
setcookie( 'sprak', $my_cookie, time() + 60*60*24*365, COOKIEPATH, COOKIE_DOMAIN );
$language = $my_cookie;
}
} else {
if( isset( $_COOKIE['sprak'] ) ) {
$language = $_COOKIE['sprak'];
} else {
/* This function checks the $_SERVER['HTTP_ACCEPT_LANGUAGE'] */
$language = rps_detectlanguage();
}
}
}
add_action( 'wp', 'rps_set_language_preferences' );
But... It doesn't work!
If I try to set a cookie by hooking into 'wp' I need to refresh my screen twice before the cookie appears. I guess it's not being set in time, but I don't know how to make sure that it will be!
Any advice?