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?

1 Answer 1


I've been able to set cookies properly at both the template_redirect and init action hooks. You might try using one of those instead.

  • I'd recommend init because it makes more sense logically, assuming someone else will look at the code and try to figure out when/where the cookie is being set.
    – EAMann
    Commented Nov 30, 2011 at 23:11
  • Hi @Otto - I tried this already (sorry, should've said that in my post). The 'wp' hook was a bit of a shot in the dark! Unfortunately it doesn't solve the issue for me, now I'm even less sure why..! Commented Dec 1, 2011 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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