i’ve been looking the whole day how to setcookies in wordpress. in my way i found out (using the developer toolbar) that the cookie is set but still not working.
i have 2 files the first contains the login form redirecting to another page to set the cookie and return to another page to check if it’s working. domain which is tested on is like this : blog.mydomain.com. here’s the setcookie file :
<?php
setcookie("user_name","test",time()+3600);
?>
and chcking the cookie like this :
if(isset($_COOKIE["user_name"])){
echo "cookie exists";
}
else{
echo "cookie doesn't exist";
}
i’ve read many topics about this issue but there was no clear answer.
Thanks in advance
This typically happens when you try to set a cookie after sending output to the browser. To set a cookie in WP, you should use the ‘init’ hook to set the cookie on init.
well, my best way to use cookie in wordpress is this,
i used this the function to setcookie in wp hook of wordpress. the main reason of this is that we may need sometime current page or post, that we cannot access on init hook, but we can access in wp hook.
now, in a shortcode or other plugin/theme functions we may just need to check if the cookie exists or not. thats it
Another option is to use PHP’s
ob_start();
andob_end_flush();
.You can find documentation on the two functions here
The way I resolved my issues was to call the two functions before and after the opening and closing html tags like this:
The issue I was running into was calling a global function that used PHP’s
setcookie();
and because WordPress processes the page progressively, the cookie couldn’t be created due to the page’s headers already being sent.PHP’s output buffering function forces the headers to be sent before WordPress processes the page.
Hope this helps.