Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

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.

share|improve this answer
    
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 Nov 30 '11 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..! –  Richard Sweeney Dec 1 '11 at 7:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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