Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
like image 897
user1269625 Avatar asked Aug 03 '12 02:08

user1269625


2 Answers

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 */
like image 181
Jerome Ansia Avatar answered Sep 24 '22 19:09

Jerome Ansia


  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 );
    
like image 26
Reza Mamun Avatar answered Sep 25 '22 19:09

Reza Mamun