0

I'm trying to set a custom cookie in Wordpress. This code is in my theme's functions.php. I'm getting all of the echos, but it will not create the cookie and I'm stumped. This should have taken 5 minutes and I cannot figure out why it HATES me!

It's using the 'init' hook and therefore should be processed BEFORE the headers are sent!

add_action( 'init', 'checking_my_cookie' );

function setting_my_first_cookie() {
   setcookie( 'unicorn', 'cupcakes', 30 * DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, true, false);
}
function checking_my_cookie(){
   if(!isset($_COOKIE['unicorn'])) {
     setting_my_first_cookie();
   } else {
   }
}
Jen Born
  • 741
  • 1
  • 6
  • 20
  • *Especially* after an `echo` you won't be able to send any more cookies *in an HTTP header* anymore. Check your error log. – deceze Apr 19 '18 at 15:49
  • that's a very valid point. i've removed the echos (that i was using diagnostically, btw) and it's STILL not working – Jen Born Apr 19 '18 at 16:03
  • Have you checked your error logs and/or activated error reporting? – deceze Apr 19 '18 at 16:07
  • I just checked them, there were errors, but not anymore and it's still not working – Jen Born Apr 19 '18 at 16:26
  • I obviously don't know why it's doing this or how to fix it, but it appears to be putting the cookie into Local storage in Chrome. It doesn't have a name for some reason. Do you know how to fix this? – Jen Born Apr 19 '18 at 16:44
  • Looks at Chrome’s Network inspector, what exactly is the `Set-Cookie` HTTP response header? – deceze Apr 19 '18 at 17:15
  • THANK YOU!!! I looked at it and it showed me that the max age was 0 and the expiration date was in 1970. apparently, this doesn't work: 30 * DAY_IN_SECONDS – Jen Born Apr 19 '18 at 18:59

0 Answers0