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:
<?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(){
$path = parse_url(get_option('siteurl'), PHP_URL_PATH);
$host = parse_url(get_option('siteurl'), PHP_URL_HOST);
$expiry = strtotime('+1 month');
setcookie('my_cookie_name_1', 'my_cookie_value_1', $expiry, $path, $host);
/* more cookies */
setcookie('my_cookie_name_2', 'my_cookie_value_2', $expiry, $path, $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
- …
Update
you should also be able to use the COOKIE_PATH and COOKIEDOMAIN constants rather than figuring them out yourself, which I just noticed in Andre R Kohl’s answer – drzaus