非插件纯代码实现WordPress增加浏览次数统计及显示评论数

admin wordpress评论854字数 2138阅读模式

统计浏览次数

这个功能做得比较简单,没有做用户及ip去重,只是单纯的统计页面打开次数,将下面代码加入模板的function.php中即可

  1. /** 
  2.  * 设置阅读次数 
  3.  * 注意count_key, 后续都是根据这个来统计的 
  4.  */  
  5. function set_post_views () {     
  6.     global $post;     
  7.     $post_id = $post -> ID;     
  8.     $count_key = 'views';     
  9.     $count = get_post_meta($post_id, $count_key, true);    
  10.     if (is_single() || is_page()) {     
  11.         if ($count == '') {     
  12.             delete_post_meta($post_id, $count_key);     
  13.             add_post_meta($post_id, $count_key, '0');     
  14.         } else {     
  15.             update_post_meta($post_id, $count_key, $count + 1);     
  16.         }     
  17.     }     
  18. }     
  19. add_action('get_header', 'set_post_views');    

获取浏览次数

下面函数可以获取浏览次数,在需要显示的地方调用即可

  1. /** 
  2.  * 阅读次数 
  3.  * count_key与set函数的count_key一致 
  4.  */  
  5. function get_post_views ($post_id) {     
  6.     $count_key = 'views';     
  7.     $count = get_post_meta($post_id, $count_key, true);     
  8.     if ($count == '') {     
  9.         delete_post_meta($post_id, $count_key);     
  10.         add_post_meta($post_id, $count_key, '0');     
  11.         $count = '0';     
  12.     }     
  13.     echo number_format_i18n($count);     
  14. }  

使用示例

最常规的使用应该是文章详情中,一般是文章页面 (single.php)的while ( have_posts() )后面,部分single.php中有get_template_part( ‘template-parts/content’, ‘single’);则需要到conent加上下面的代码

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

显示评论次数

在上面浏览次数之后,可以加上评论次数显示

  1. <?php get_post_views($post -> ID); ?> 阅读  
  2. &#160;/&#160;  
  3. <?php comments_number('暂无评论', '1条评论', '% 评论' );?>  

在后台文章列表统计中增加浏览次数

  1. require_once( trailingslashit( get_template_directory() ) . 'trt-customize-pro/newslite/class-customize.php' );  
  2.   
  3. //在后台文章列表增加一列数据  
  4. add_filter( 'manage_posts_columns', 'ashuwp_customer_posts_columns' );  
  5. /** 
  6.  * 注意"views"需要与之前统计set方法一致 
  7.  */  
  8. function ashuwp_customer_posts_columns( $columns ) {  
  9.     $columns['views'] = '浏览次数';  
  10.     return $columns;  
  11. }  
  12.    
  13. //输出浏览次数  
  14. add_action('manage_posts_custom_column', 'ashuwp_customer_columns_value', 102);  
  15.   
  16. /** 
  17.  * 注意"views"需要与之前统计set方法一致 
  18.  */  
  19. function ashuwp_customer_columns_value($column, $post_id){  
  20.     if($column=='views'){  
  21.         $count = get_post_meta($post_id, 'views', true);  
  22.         if(!$count){  
  23.             $count = 0;  
  24.         }  
  25.         echo $count;  
  26.     }  
  27.     return;  
  28. }  

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
admin
  • 本文由 发表于 2021年9月27日 17:50:13
  • 转载请务必保留本文链接:https://www.58pxe.com/7724.html
匿名

发表评论

匿名网友 填写信息

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