wp/wordpress文章页面添加阅读量/点击量,后台并显示阅读量
wordpress默认不带阅读量的,现在加上。在function.php加入代码
1、前端加入阅读量和点击量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //增加文章阅读次数 function record_visitors(){ if (is_singular()){ global $post ; $post_ID = $post ->ID; if ( $post_ID ){ $post_views = (int)get_post_meta( $post_ID , 'views' , true); if (!update_post_meta( $post_ID , 'views' , ( $post_views +1))){ add_post_meta( $post_ID , 'views' , 1, true); } } } } add_action( 'wp_head' , 'record_visitors' ); function post_views( $before = '(点击 ' , $after = ' 次)' , $echo = 1){ global $post ; $post_ID = $post ->ID; $views = (int)get_post_meta( $post_ID , 'views' , true); if ( $echo ) echo $before , number_format( $views ), $after ; else return $views ; } |
在线显示的地方,例如singe.php页面加入:
<?php post_views('','次');?>
2、后台的管理页面,加上阅读量
//在后台文章列表增加一列数据 add_filter( 'manage_posts_columns', 'customer_posts_columns' ); function customer_posts_columns( $columns ) { $columns['views'] = '浏览次数'; return $columns; } //输出浏览次数 add_action('manage_posts_custom_column', 'customer_columns_value', 10, 2); function customer_columns_value($column, $post_id){ if($column=='views'){ $count = get_post_meta($post_id, 'views', true); if(!$count){ $count = 0; } echo $count; } return; }
文章如果根据阅读量排序,可以
1 $hot_args = array( 2 'cat' => $hot_category_id, // 使用分类ID 3 'posts_per_page' => 6, // 获取所有文章 4 'ignore_sticky_posts' => 1, // 忽略置顶文章 5 'has_post_thumbnail' => true, // 只获取带有特色图片的文章 6 'meta_key' => 'views', 7 'orderby' => 'meta_value', 8 9 'order' => 'DESC' // 倒序排列 10 );
就是排序条件
6 'meta_key' => 'views', 7 'orderby' => 'meta_value',
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!