您好,欢迎访问一九零五行业门户网

详解WordPress文章阅读量如何统计和显示(非插件)

下面由wordpress教程栏目给大家介绍wordpress文章阅读量统计和显示(非插件, 刷新页面不累加),希望对需要的朋友有所帮助!
wordpress文章阅读量统计和显示(非插件, 刷新页面不累加)wordpress文章阅读量统计实现思路:
每进入一次文章详情页面, 就会通过cookie判断该用户是否在设定的过期时间内访问过该文章, 若没有访问过, 则浏览次数增加一次。
实现流程如下:
1.添加以下代码至主题的functions.php文件, 放在该文件最下面即可:
function getpostviews($postid){    $count_key = 'views';    $count = get_post_meta($postid, $count_key, true);    if($count=='' || !$count){        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);    }}
2.添加以下代码至主题的single.php 文件, 时间间隔可自定义设置, 放在该文件最上面即可:
<?php if(!isset($_cookie['views'.$post->id.cookiehash]) || $_cookie['views'.$post->id.cookiehash] != '1'){    setpostviews($post->id);    setcookie('views'.$post->id.cookiehash,'1',time() + 99999999,cookiepath,cookie_domain);} ?>
3.将以下代码添加到要显示浏览次数的位置, 例如 文章列表(template-parts/content.php), 文章详情页面(template-parts/content-single.php), 搜索结果页面(template-parts/content-search.php)等。
<?php echo getpostviews(get_the_id());?>
以下是我的个人博客  添加展示阅读量的代码和实际显示效果。
以上就是详解wordpress文章阅读量如何统计和显示(非插件)的详细内容。
其它类似信息

推荐信息