免插件统计WordPress文章阅读数

Author: 陌小雨Date: 2016-02-01View: 55

自己制作主题的话,就会需要这些小技巧了,现成的主题一般都自己集成。

20160201115420

//文章点击数
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 View";
    }
    return $count.' Views';
}
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);
    }
}

调用方法:粘帖下面代码到主题single.php文件loop循环中:

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

在需要显示的地方调用:

<?php echo getPostViews(get_the_ID()); ?>

代码弊端:刷新一次阅读数就+1,统计出来的不是最真实的。