我们在用一些主题的时候,是自带文章浏览统计量的,但每刷新一次就算作一次浏览,特别是像本站这样有google adsense的网站,发布文章后,会手动刷新页面来使广告生效,就造成浏览量会变很多,今天本给大家介绍一下刷新不再计入浏览量的代码。
在wordpress主题的functions.php里加入以下代码:
/** * WordPress 刷新页面不计入浏览量 * https://www.depaisi.com */ 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); } }
解决刷新统计数增加,一定要放在文章页面的最前面,不过php设置cookie之前不能有输出,本站的主题是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文章阅读量如何统计和显示(非插件)的详细内容。我们主要看的是第二段代码,因为第一段代码就是普通wordpress文章浏览量的代码,第二段代码才是起决定性作用的,如果有不懂的地方可以给本站留言哦~
PS:也会有失效的情况,实在不行的建议用插件实现这个功能。推荐:Post Views Counter
相关文章推荐: