How to use setcookie in Page views counter function

I have this function for Page views counter:

function PageViews($postID) {
$c_key = 'views_count';
$cookie_count = $_COOKIE['views_count_'.$postID];
$count = get_post_meta($postID, $c_key, true);
if(!$cookie_count){
    setcookie('views_count_'.$postID , 'view', time()+999999999);
    if($count == ''){
        $count = 1;
        update_post_meta($postID, $c_key, $count);
        return $count;
    }else{
        $count++;
        update_post_meta($postID, $c_key, $count);
        return $count;
    }
}else{
    return $count;
}
}

when I go to view post I get this error:

Read More
Warning: Cannot modify header information - headers already sent by (output started at....

and my cookie doesn’t set, this function in function.php . how to set this cookie ?

Related posts

Leave a Reply

1 comment

  1. You are trying to set the cookie after output has already been sent to the browser. This is not allowed. You need to call this function before any output is generated.