Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to set cookies to re-route returning users to my a specific page within my Wordpress site.

I'd like some advice with these 2 things:

  1. Where in the Wordpress php files should cookies be checked before loading any content to handle a redirect? Is there a good file this should exist in over others?
  2. How do I properly set a cookie within Wordpress? setcookie('cookie_name', 'cookie_value', time()+4000); doesn't seem to be saving any cookies to my system.
share|improve this question
Ah, realized I needed to hook this into the init(). SOLUTION: I created a function in functions.php that would set and check the cookie. for this to work properly, after defining the function, outside the function call this: add_action('init', 'function-name'); – Atticus Jul 2 '11 at 4:07
4  
You are allowed to answer your own question... – The Shadow Jul 2 '11 at 4:12
2  
In fact, it's explicitly encouraged. Please do answer it yourself. I'm also sending this to WordPress.SE, since it seems more appropriate there. – Michael Myers Jul 2 '11 at 4:49
Thanks guys -- i did not realize there was a Wordpress area. And thanks for the tip to answer myself :) APpreciated, +1s. – Atticus Jul 5 '11 at 4:34

migrated from stackoverflow.com Jul 2 '11 at 4:50

2 Answers

up vote 4 down vote accepted

Ah, realized I needed to hook this into the init().

SOLUTION: I created a function in functions.php that would set and check the cookie. for this to work properly, after defining the function, outside the function call this: add_action('init', 'function-name'); – Atticus

share|improve this answer

1 - You can check for cookies and do your redirect using hooks that are called before any output like the 'init' hook:

<?php

// Hook the function "redirect()" on to the "init" action
add_action('init', 'redirect');

// redirect() may redirect the user depending on the cookies he has
function redirect(){
  /* CODE */
}

?>

2 - The best way to set cookies would be using the 'init' hook like this:

<?php

add_action('init', 'my_setcookie');

// my_setcookie() set the cookie on the domain and directory WP is installed on
function my_setcookie(){
  setcookie(
    'my_cookie_1', 
    1, 
    strtotime('+1 month'), 
    parse_url(get_option('siteurl'), PHP_URL_PATH), 
    parse_url(get_option('siteurl'), PHP_URL_HOST)
  );
}

?>

This is more consistent, if you have a blog at www.example.com/blog, the coockie(s) will not be available at

  • www.example.com
  • www.example.com/store
  • example.com
  • www2.example.com
  • ...
share|improve this answer

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.