Wordpress - Setting custom cookies in Wordpress

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


You probably should use the constants COOIKEPATH and COOKIE_DOMAIN, existing since WP 3.0

setcookie("your_cookie", $your_value, time()+3600, COOKIEPATH, COOKIE_DOMAIN);

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'); 

Tags:

Php

Cookies