How to set a cookie in Wordpress

I am trying to set a cookie in wordpress. I have my own cookie:

<?php setcookie('test', 'test', 0, '/', '/');  ?>

in header.php of my theme, but when I go to my browser to view my site, 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 is not set. How to set cookie in wordpress?

I also tried this

 function set_new_cookie() {
    setcookie('test', 'test', 0, '/', '/');
}
add_action( 'init', 'set_new_cookie');
+5
source share
2 answers

You must install them before anything comes out.

look there: How to set, receive and delete cookies in Wordpress?

If you use a theme in function.php

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

Your expiration time is 0 so that you immediately delete cookies on php doc:

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

You should install it like this:

setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
+3
  • cookie: cookie, (60 * 60 ), COOKIEPATH COOKIE_DOMAIN, WordPress .

    setcookie( 'my-cookie-name', 'my-cookie-value', time() + 3600, COOKIEPATH, COOKIE_DOMAIN );
    
  • cookie: cookie $_COOKIE, .

    $myCookie = isset( $_COOKIE['my-cookie-name'] ) ? $_COOKIE['my-cookie-name'] : 'Not Set!!';
    
  • cookie: № 1, cookie;

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

All Articles