免插件实现WordPress文章阅读次数
一般为Wordpress推荐阅读:为WordPress文章作者评论留言显示“文本作者”提示文章添加阅读次数统计,会用到wp-postviews或者wp-postviews-plus插件,这里分享两段不用插件实现Wordpress文章阅读次数的代码,供大家参考。
代码一:
一、首先将下面代码加到主题functions模版文件中:
- 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);
- }
- }
二、接下来将下面代码加到主题single模版主循环的中:
- <?php setPostViews(get_the_ID()); ?>