wordpress中无插件实现文章点击浏览次数
笔者在使用WP-PostViews插件时,发现其并不完全能统计文章浏览情况,有的文章始终是0,因此经过测试,搞到一些不用插件的办法实现文章浏览点击次数。
工具/原料
富文本编辑器,推荐editplus;模板文件。
方法/步骤
1
停用后台WP-PostViews或者相关的浏览统计插件;备份模板文件。
2
在你使用的博客主题里面,找到function.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 View";
}
return $count.' Views';
}
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);
}
}
3
打开single.php,找到以下代码 <?php the_tags('', ', ', ' / '); ?> 在这段代码后面追加以下代码:
<?php setPostViews(get_the_ID()); ?>
<?php echo getPostViews(get_the_ID()); ?>
或者,只要在循环体开始后的任何位置加上以上代码都是可以的。
4
打开loop.php,找到以下代码 <?php the_tags('', ', ', ' / '); ?> 在这段代码后面追加以下代码:
<?php echo getPostViews(get_the_ID()); ?>
或者,只要在循环体开始后的任何位置加上以上代码都是可以的。
OK了,到此就实现了不用插件就可以实现浏览次数的效果了。