wordpress统计阅读次数

瘦欲@ 提交于 2020-01-17 09:46:20
本文介绍怎样统计文章的阅读次数。先贴代码:

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);
    }
}

包含两个函数,
setPostViews($postID) 设置某篇文章的阅读次数
getPostViews($postID) 读取某篇文章的阅读次数
实际上,阅读次数是存储在wp_postmeta表中meta_key= 'post_views_count'对应的meta_value中。

使用方法:将上面两个函数,添加到模板文件functions.php中,在single.php页面中显示文章标题或内容的前后,调用setPostViews($postID);在需要显示文章阅读次数的页面(如首页,分类页面等)对应的模板的相应位置调用getPostViews($postID)。


这可能只是一个临时解决方案,对于浏览量很大的站点,每次阅读页面都去读写数据库可能会给数据库增加很多负载。有问题请留言,有更好的解决方案,也可以贴出来交流。
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!