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:
- 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?
- 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.
1 – You can check for cookies and do your redirect using hooks that are called before any output like the ‘init’ hook:
2 – The best way to set cookies would be using the ‘init’ hook like this:
This is more consistent, if you have a blog at http://www.example.com/blog, the coockie(s) will not be available at
Update
You probably should use the constants
COOIKEPATH
andCOOKIE_DOMAIN
, existing since WP 3.0Ah, 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:
This way worked :
You will want to delete your cookie before any content is written to the page (before headers are sent).
To set the cookie, include the path, domain, and I also recommend setting the last 2 parameters to true (
$secure
and$httponly
). You will also need to supply the same parameters tosetcookie()
when deleting, aside from the$expiry
(which should be negative) and the$value
(which should be empty ”).If you are passing json through the cookie, it seems like you need to
base64_encode
it as well, or it won’t properly decode.All of this should be done in a class so you can access the value of the cookie later on in your code. The class can be added to a plugin or functions.php.
Here is an example where we use a cookie to store an action response to then display it to the user after we redirect them:
You can then set the cookie via:
my_custom_class::some_action_that_sets_the_cookie('the message');