如何在 WordPress 主题中统计文章阅读量?
WORDPRESS建站
12/5/20241 分钟阅读
如何在 WordPress 主题中统计文章阅读量?
WordPress 核心程序并没有文章阅读统计功能。为了实现对文章阅读量的统计和展示,可以选择使用插件或进行代码修改。
插件简介
WP-PostViews
Post Views Counter
这种都有很多,过多的插件势必导致网站臃肿
我更喜欢下面的代码修改
代码修改
添加以下代码至主题的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); } }
添加以下代码至主题的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); } ?>
将以下代码添加到要显示浏览次数的位置, 例如 文章列表(template-parts/content.php), 文章详情页面(template-parts/content-single.php), 搜索结果页面(template-parts/content-search.php)等。
<?php echo getPostViews(get_the_ID());?>