免插件实现WordPress文章阅读次数

免插件实现WordPress文章阅读次数

一般为Wordpress文章添加阅读次数统计,会用到wp-postviews或者wp-postviews-plus插件,这里分享两段不用插件实现Wordpress文章阅读次数的代码,供大家参考。

代码一:

一、首先将下面代码加到主题functions模版文件中:

  1. function getPostViews($postID){   
  2.     $count_key = 'post_views_count';   
  3.     $count = get_post_meta($postID$count_key, true);   
  4.     if($count==''){   
  5.         delete_post_meta($postID$count_key);   
  6.         add_post_meta($postID$count_key, '0');   
  7.         return "0 View";   
  8.     }   
  9.     return $count.' Views';   
  10. }   
  11. function setPostViews($postID) {   
  12.     $count_key = 'post_views_count';   
  13.     $count = get_post_meta($postID$count_key, true);   
  14.     if($count==''){   
  15.         $count = 0;   
  16.         delete_post_meta($postID$count_key);   
  17.         add_post_meta($postID$count_key, '0');   
  18.     }else{   
  19.         $count++;   
  20.         update_post_meta($postID$count_key$count);   
  21.     }   
  22. }  

二、接下来将下面代码加到主题single模版主循环的中:

  1. <?php setPostViews(get_the_ID()); ?>  

也就是类似这句的下面

  1. <?php if (have_posts()) : while (have_posts()) : the_post(); ?>  

三、最后,将调用显示阅读次数代码加到single模版适当的位置:

  1. <?php echo getPostViews(get_the_ID()); ?>  

如果想在其它位置显示阅读次数,可以将下面代码也加到functions模版中:

  1. remove_action('wp_head','adjacent_posts_rel_link_wp_head',10,0);  

 

原文:Track post views without a plugin using post meta

代码二:

一、同样将下面代码加到主题functions模版文件中:

  1. //postviews   
  2. function get_post_views ($post_id) {   
  3.   
  4.     $count_key = 'views';   
  5.     $count = get_post_meta($post_id$count_key, true);   
  6.   
  7.     if ($count == '') {   
  8.         delete_post_meta($post_id$count_key);   
  9.         add_post_meta($post_id$count_key, '0');   
  10.         $count = '0';   
  11.     }   
  12.   
  13.     echo number_format_i18n($count);   
  14.   
  15. }   
  16.   
  17. function set_post_views () {   
  18.   
  19.     global $post;   
  20.   
  21.     $post_id = $post -> ID;   
  22.     $count_key = 'views';   
  23.     $count = get_post_meta($post_id$count_key, true);   
  24.   
  25.     if (is_single() || is_page()) {   
  26.   
  27.         if ($count == '') {   
  28.             delete_post_meta($post_id$count_key);   
  29.             add_post_meta($post_id$count_key, '0');   
  30.         } else {   
  31.             update_post_meta($post_id$count_key$count + 1);   
  32.         }   
  33.   
  34.     }   
  35.   
  36. }   
  37. add_action('get_header', 'set_post_views');  

二、将调用显示阅读次数代码加到single模版适当的位置:

  1. <?php get_post_views($post -> ID); ?> views  

调用显示阅读次数代码也可以加到其它模版文件的适当位置。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值