当前位置: 首页 > 虚拟主机 > 正文

如何通过代码实现WordPress文章浏览次数统计功能

这个功能相信大部分博客都会用到,今天介绍的使用插入代码的方式来实现这一功能,代码盲或者懒得折腾代码的童鞋可以使用这个插件:WP-PostViews

首先进入WP后台,主题 – 编辑,找到functions.php文件,在适当位置插入下面代码:

/* Postviews start */
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);
    }
}
/* Postviews start end*/

然后在single.php中的 endwhile; endif; wp_reset_query(); 循环前添加如下代码:

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

最后在你想要显示文章浏览次数统计的地方(一般在index.php、sidebar.php或single.php文件) 添加如下代码即可。

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

本文固定链接: https://blog.wsisp.com/535 | 网硕互联团队博客

avatar
该日志由 网硕互联 于2013年03月06日发表在 虚拟主机 分类下,
原创文章转载请注明: 如何通过代码实现WordPress文章浏览次数统计功能 | 网硕互联团队博客
关键字: , , ,

报歉!评论已关闭.