I’m trying to set a cookie in wordpress. I have my cookie set like this :
<?php setcookie('test', 'test', 0, '/', '/'); ?>
in header.php of my theme, but when I go to my browser to view my website I get this error
Warning: Cannot modify header information - headers already sent by (output started at /home/content/19/9468119/html/wp-content/themes/twentyeleven/header.php:27) in /home/content/19/9468119/html/wp-content/themes/twentyeleven/header.php on line 201
and also my cookie doesnt set. How do I set a cookie in wordpress?
I have also tried this
function set_new_cookie() {
setcookie('test', 'test', 0, '/', '/');
}
add_action( 'init', 'set_new_cookie');
You have to set them before anything is outputted
look there: How can I set, get and destroy cookies in WordPress?
If you are using a theme in function.php
Your expiration date is 0 so you cookies will be deleted right away look at the php doc:EDIT:
From php.net:
http://php.net/manual/en/function.setcookie.php
You have to set it like this for example :
Setting a Cookie:
The below example will set the cookie that expired for one hour (60*60 seconds) since it set with COOKIEPATH and COOKIE_DOMAIN was defined by WordPress according to your site path and domain.
Getting a Cookie:
Getting a cookie can be done by using variable $_COOKIE which contains an associative array.
Delete or Unset a Cookie: It is same as the above instruction #1, just with a negative time to expire the cookie;