need the right way to setcookie in wordpress

2019-08-01 15:48发布

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

3条回答
ゆ 、 Hurt°
2楼-- · 2019-08-01 15:50

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.

function set_username_cookie() {
    if (!isset($_COOKIE['user_name'])) {
        setcookie("user_name","test",time()+3600);
    }
}
add_action( 'init', 'set_username_cookie');
查看更多
▲ chillily
3楼-- · 2019-08-01 15:58

Another option is to use PHP's ob_start(); and ob_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:

<?php ob_start(); ?>
<!DOCTYPE html>
<html>
  <head>
  </head>
<body>
  <?php /* Wordpress loop and other tempate code here */ ?>
</body>
</html>
<?php ob_end_flush(); ?>

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.

查看更多
甜甜的少女心
4楼-- · 2019-08-01 16:10

well, my best way to use cookie in wordpress is this,

function set_my_cookie() {
global $post;
$post_id  = $post->ID;  
$cookie_name = "my_cookie";
$cookie_value = "my_cookie_val";
if (!isset($_COOKIE['my_cookie'])) {
{
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); 
}}add_action( 'wp', 'set_my_cookie');

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

查看更多
登录 后发表回答