WordPress不使用(PostViews)插件,实现浏览统计功能

使用代码的方式来实现浏览统计功能,只要我们手动将代码添加到主题文件里面就可以简单的实现统计,虽然比起插件功能和设置要简单的多,不过针对一些不喜欢使用插件的朋友来说,这个方法还是不错滴,下面磊子就把代码给大家贴出来(代码来自网络)。

首先在所使用主题文件目录中找到functions.php文件,在最底位置插入下面代码:

<?php
02 /* Postviews start */
03 function getPostViews($postID){
04     $count_key 'post_views_count';
05     $count = get_post_meta($postID$count_key, true);
06     if($count==''){
07         delete_post_meta($postID$count_key);
08         add_post_meta($postID$count_key'0');
09         return " 0 ";
10     }
11     return $count;
12 }
13 function setPostViews($postID) {
14     $count_key 'post_views_count';
15     $count = get_post_meta($postID$count_key, true);
16     if($count==''){
17         $count = 0;
18         delete_post_meta($postID$count_key);
19         add_post_meta($postID$count_key'0');
20     }else{
21        $count++;
22         update_post_meta($postID$count_key$count);
23     }
24 }
25 /* Postviews start end*/
26 ?>

这里面要注意”<?php  ?>” 根据你的functions.php文件里面的代码来决定是否要添加。

功能代码添加好后,我们开始进行统计,在single.php中的 endwhile; endif;  循环前添加如下代码:

1 <?php setPostViews(get_the_ID());  ?>

统计代码添加好后,接着便是进行调用统计次数,我们可以在任何地方进行添加(一般在index.php、sidebar.php或single.php文件等)。

 
1 <?php echo getPostViews(get_the_ID()); ?> 次浏览

这样一个简单的浏览统计功能就做好了,有些朋友可能会觉得刷新详细页面(single.php),统计次数也会增加,这样统计的数目就会变得不真实,没错这块代码的确会出现这个问题。 如果你想尽量做到统计真实的话,你可以研究下利用IP和cookie来对这统计代码进行修改,喜欢折腾的朋友可以尝试下。

posted @ 2014-03-06 13:23  wordpress技术方舟  阅读(1193)  评论(0编辑  收藏  举报