这个功能相信大部分博客都会用到,今天介绍的使用插入代码的方式来实现这一功能,代码盲或者懒得折腾代码的童鞋可以使用这个插件: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 文件) 添加如下代码即可。