免插件实现wordpress文章浏览阅读次数

WordPress教程 4825

给wordpress添加每篇文章的阅读次数可以有效知道博客最受欢迎的文章,前面博客吧介绍了WordPress 博客文章浏览数统计插件WP-PostViews,可以很好地实现这个功能效果,但对于代码控来说,多一个插件就是多一份痛苦,能不用插件实现的东西绝对选择代码,而wordpress文章浏览数统计也可以通过代码实现。

wordpress非插件实现文章浏览次数统计:

在当前主题的functions.php文件里添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
    统计文章浏览次数
*/
function getPostViews($postID){
    $count_key = 'views';
    $count = get_post_meta($postID, $count_key, true);
    if($count=='' || !$count){
        // delete_post_meta($postID, $count_key);
        // add_post_meta($postID, $count_key, '0');
        return "0";
    }
    return $count;
}
function setPostViews($postID){
    $count_key = 'views';
    $count = get_post_meta($postID, $count_key, true);
    if($count=='' || !$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);
	}
}
function countViews(){
    global $wpdb;
    $count=0;
    $views= $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key='views'");
    foreach($views as $key=>$value) {
        $meta_value=$value->meta_value;
        if($meta_value!=''){
            $count+=(int)$meta_value;
        }
    }
    return $count;
}

附:以上代码用到的函数:

1
2
3
4
5
get_post_meta();
delete_post_meta();
add_post_meta();
update_post_meta();
$wpdb->get_results($sql);

主题调用显示:

首页文章调用:在首页文章的循环里添加以下调用代码显示阅读次数

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

文章页面single.php或自定义页面添加调用代码

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

整站文章阅读次数统计调用代码

1
<?php echo countViews(); ?>

效果参考博客吧右下角的浏览总数

精品推荐: