Akash Gajbhiye Akash Gajbhiye - 4 months ago 31
PHP Question

cookies not working in wordpress

I've created a meta field 'priority_priority' so that I can sort post based on how many times they have been visited..least visited post gets more priority. so whenever a visitor visits the post the priority variable is decremented.but I want priority to be decremented only on the first visit from the same user so am using cookies but the following code in not working the priority is always decremented and

var_dump($_COOKIE['visitor'.$post_id])


always gives NULL

$post_id = get_the_ID();
$priority = get_post_meta($post_id,'priority_priority',true);
if($priority>1)
{
if(!isset($_COOKIE['visitor'.$post_id]))
{
$bool=setcookie('visitor'.$post_id,$post_id,DAY_IN_SECONDS,'/');
if(count($_COOKIE) > 0)
{
$priority = $priority-1;
update_post_meta($post_id,'priority_priority',$priority);
}
}

}
get_header();
?>

<div id="primary" class="content-area">

<main id="main" class="site-main site-main--single" role="main">
<div>
test
<?php var_dump($_COOKIE['visitor'.$post_id]);?>
</div>
</main><!-- #main -->

</div><!-- #primary -->




Answer
**Add this Function in functions.php**

function set_user_cookie() {
    $test = "fyjfhjf";
    setcookie('default_school', $test, time()+3600);
}
add_action( 'init', 'set_user_cookie');


**To display**
echo $_COOKIE['default_school'];