我们看到很多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 页面添加需要位置的显示代码