WordPress纯代码统计文章浏览次数

1.在主题的 functions.php文件的最后一个 ?> 前面添加下面的代码:

 
  1. //设置文章访问次数----------------------------------------------------------开始   
  2. function record_visitors()   
  3. {   
  4.     if (is_singular())   
  5.     {   
  6.       global $post;   
  7.       $post_ID = $post->ID;   
  8.       if($post_ID)   
  9.       {   
  10.           $post_views = (int)get_post_meta($post_ID, 'views', true);   
  11.           if(!update_post_meta($post_ID, 'views', ($post_views+1)))   
  12.           {   
  13.             add_post_meta($post_ID, 'views', 1, true);   
  14.           }   
  15.       }   
  16.     }   
  17. }   
  18. add_action('wp_head', 'record_visitors');   
  19. /// 函数名称:post_views   
  20. /// 函数作用:取得文章的阅读次数   
  21. function post_views($before = '(点击 ', $after = ' 次)', $echo = 1)   
  22. {   
  23.   global $post;   
  24.   $post_ID = $post->ID;   
  25.   $views = (int)get_post_meta($post_ID, 'views', true);   
  26.   if ($echo) echo $before, number_format($views), $after;   
  27.   else return $views;   
  28. //设置文章访问次数----------------------------------------------------------结束 

2.在需要显示该统计次数的地方使用下面的代码调用:

  1. 文章被阅读:<?php post_views(' ', ' 次'); ?>  
原文地址:https://www.cnblogs.com/wpxuexi/p/6380173.html