如何在Page views计数器功能中使用setcookie

时间:2013-11-25 22:40:09

标签: php wordpress cookies

我对Page views计数器有这个功能:

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;
}
}

当我去查看帖子时,我收到此错误:

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

并且我的cookie未设置,此功能在function.php中。如何设置这个cookie?

1 个答案:

答案 0 :(得分:0)

您正在尝试在输出已发送到浏览器后设置cookie。这是不允许的。您需要在生成任何输出之前调用此函数。