wordpress添加文章浏览统计(刷新不重复)

wordpress本身不带文章浏览统计,可以用插件wp-postview,但是刷新还是算一个浏览次数。

1.首先在主题下functions.php里增加以下代码,这段代码也是网上可以找到的

 //add by charleswu
function getPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if ($count == '') {
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0";
}
return $count;
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if ($count == '') {
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}

2.解决刷新统计数增加,一定要放在文章页面的最前面,貌似php设置cookie之前不能有输出,蛋疼。我的是single.php页面

 <?php
$post_id=get_the_ID();
if(isset($_COOKIE['views'.$post_id.COOKIEHASH]) && $_COOKIE['views'.$post_id.COOKIEHASH] == '1')
{ }
else{
setPostViews($post_id);
setcookie('views'.$post_id.COOKIEHASH,'1',time() + 3600,COOKIEPATH,COOKIE_DOMAIN);//设置时间间隔
}
?>
上一篇:WordPress 非插件实现拦截无中文留言


下一篇:wordpress 不用插件添加友情链接