通过代码实现真实的WordPress阅读浏览量统计

我们看到很多WordPress自带的主题有访客浏览阅读量数值显示的,但是有些时候我们在刷新页面就会自动增加。实际上这样的用户体验是不够准确的,理应是一个用户就显示一次阅读量,不会因为再次刷新而增加。于是我们在制作WordPress主题的时候,可以通过下面的方法来实现不因刷新而变动的浏览阅读量。

第一、自定义函数

在主题的 Functions.php 文件中添加代码

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

第二、添加页面代码

在 Single.php 页面添加需要位置的显示代码

推荐站内搜索:韩国服务器推荐、美国主机推荐、服务器如何加防御、云服务器vps、香港cn2服务器、秒换ip服务器、免费国际域名、免费asp空间申请、vps服务器租用、免费国内空间、