设计本版爱情花园主题时,为了“低碳”省去了文章计数功能,经过较长一段时间测试后,发现少了这个计数功能也少了很多的乐趣,于是决定把这个功能添加进去。
功能实现很简单,为获得更合理的数据信息,添加了防刷新功能:
第一步:在主题functions.php文章加添加如下代码:
/*******************************
文章浏览计数器(显示文章浏览次数)
需要显示的位置添加:echo getPostViews(get_the_ID());
每篇文章的主循环加:setPostViews(get_the_ID());
********************************/
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';
$ViewedIDlist = $_COOKIE['ArticleIsViewed'];
$ViewidIsNull = False; //文章是否已阅读变量,为True时表示需要涮新阅读量
if(empty($ViewedIDlist)){
$ViewidIsNull = True;
}else{
$ViewidIsNull = True;
$ViewedIDarr = explode("[+]",$ViewedIDlist);
for($i=0; $i<count($ViewedIDarr); $i++){
if((int)$ViewedIDarr[$i] == (int)$postID)
$ViewidIsNull = False;
}
}
if($ViewidIsNull){
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 1;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, $count);
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
if(empty($ViewedIDlist))
setcookie('ArticleIsViewed',$postID,time()+43200);
else
setcookie('ArticleIsViewed',$ViewedIDlist.'[+]'.$postID,time()+43200);
}
}
第二步:在single.php文件的主循环内添加代码:setPostViews($post->ID); //添加文章浏览计数器
;
第三步:在需要显示文章浏览次数的文件(如:single.php,home.php和)的显示位置添加代码:echo getPostViews($post->ID);
。
很不错啊,找了很久了。还想请教一个问题,就是如何排除搜索引擎的访问?
请问原理是什么?是不是每篇文章都写入一个cookie,cookie不就超过浏览器限制了?