新安装wordpress发现没有显示文章浏览次数的功能…+.+
把下面的代码复制到主题的functions.php文件里,然后按照步骤1和步骤2的说明进行操作,就可以显示每篇文章的被浏览次数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); } } |
代码解释:添加的 getPostViews 和 setPostViews 方法分别是获取文章浏览次数和设置文章浏览次数的方法。设置方法是通过文章 ID 将浏览次数信息写入到 post_meta 也就是我们文章的“自定义栏目”内,而获取就是通过文章 ID 从 post_meta 里获取对应信息。
步骤一:
然后修改 single.php 文件,在主循环内添加如下代码:
1 2 3 | <?php setPostViews(get_the_ID()); ?> |
代码解释:这段代码的作用是调用 functions.php 里我们添加的 setPostViews 方法,以实现设置浏览次数。
最后,我们在想要显示文章浏览次数的地方添加如下代码即可。
步骤二:
1 2 3 | <?php echo getPostViews(get_the_ID()); ?> |
代码解释:作用同上,只不过是调用 getPostViews 方法,以获得浏览次数,并且打印显示。
需要注意的是这个方法在安装了缓存插件的情况下不适用。