添加WordPress文章阅读量的最简单办法

2019年12月13日23:22:28 发表评论 热度441 ℃

将下面代码添加到Functions.php

  1. //取得文章的阅读次数  
  2. function post_views($before = '点击 ', $after = ' 次', $echo = 1)  
  3. {  
  4.   global $post;  
  5.   $post_ID = $post->ID;  
  6.   $views = (int)get_post_meta($post_ID, 'views', true);  
  7.   if ($echoecho $before, number_format($views), $after;  
  8.   else return $views;  
  9. }  
  10. function record_visitors()  
  11. {  
  12.     if (is_singular()) {  
  13.       global $post;  
  14.       $post_ID = $post->ID;  
  15.       if($post_ID) {  
  16.           $post_views = (int)get_post_meta($post_ID, 'views', true);  
  17.           if(!update_post_meta($post_ID, 'views', ($post_views+1))) {  
  18.             add_post_meta($post_ID, 'views', 1, true);  
  19.           }  
  20.       }  
  21.     }  
  22. }  
  23. add_action('wp_head', 'record_visitors');  

在想调用的地方,直接在while ( have_posts() ) {内使用下面代码即可

  1. <?php post_views(); ?>  
瓜皮猪

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: