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