How to set a cookie in WordPress

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

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

Related posts

Leave a Reply

2 comments

  1. 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

    function set_new_cookie() {
        //setting your cookies there
    }
    add_action( 'init', 'set_new_cookie');
    

    Your expiration date is 0 so you cookies will be deleted right away look at the php doc:

    EDIT:
    From php.net:

    If set to 0, or omitted, the cookie will expire at the end of the
    session (when the browser closes).

    http://php.net/manual/en/function.setcookie.php

    You have to set it like this for example :

    setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
    
    1. 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.

      setcookie( 'my-cookie-name', 'my-cookie-value', time() + 3600, COOKIEPATH, COOKIE_DOMAIN );
      
    2. Getting a Cookie:
      Getting a cookie can be done by using variable $_COOKIE which contains an associative array.

      $myCookie = isset( $_COOKIE['my-cookie-name'] ) ? $_COOKIE['my-cookie-name'] : 'Not Set!!';
      
    3. Delete or Unset a Cookie: It is same as the above instruction #1, just with a negative time to expire the cookie;

      setcookie( 'my-cookie-name', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN );