好久没更新了,今天看到一道友提出这样的问题:
wordpress获取指定多少天内的热评文章列表
https://zhidao.baidu.com/question/988123512698910379.html
很长一段时间都没有看到道友能提出wordpress有质量的问题了,决定亲自分享下自己测试的方法及代码,不废话,直接看以下说明:
一、焦点
1、指定天数
这个可以通过指定日志的日期期间实现,比如
1 | post_date <= '2017-05-18' and post_date >= '2017-05-01' |
即可查询出这十几天内的文章
2、热评
统计日志评论数降序排列即可实现热评的效果
二、实现
1、方法一:使用mysql原生语句实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | global $wpdb ; $sql = "select * from $wpdb ->posts where post_date <= '2017-05-18' and post_date >= '2017-05-01' and ID in ( SELECT comment_post_ID FROM $wpdb ->comments group by comment_post_ID ORDER BY count (comment_post_ID) DESC) LIMIT 0, 20"; // SELECT comment_post_ID FROM $wpdb->comments group by comment_post_ID ORDER BY count(comment_post_ID) DESC // 统计日志评论数降序排列并返回对应的日志ID $r = $wpdb ->get_results( $sql ); //var_dump($wpdb); if ( ! is_wp_error( $r ) ) { foreach ( $r as $key => $post ) { printf( '<h1 class="entry-title" style="color:red">%s</h1>' , get_the_title( $post ->ID )) ; } } |
2、方法二:使用WP_Query和WP_Date_Query实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $post_ids = $wpdb ->get_col( "SELECT comment_post_ID FROM $wpdb->comments group by comment_post_ID ORDER BY count(comment_post_ID) DESC" ); $query_vars = array ( // https://core.trac.wordpress.org/ticket/18694#comment:4 'date_query' => array ( array ( 'before' => '2017-05-18' , 'after' => '2017-05-01' , 'inclusive' => true, ) ), 'posts_per_page' => 20 ); if ( $post_ids ) $query_vars [ 'post__in' ] = $post_ids ; global $wp_query ; $wp_query = new WP_Query( $query_vars ); //var_dump($wp_query); while ( have_posts() ) : the_post(); the_title( '<h1 class="entry-title">' , '</h1>' ); endwhile ; wp_reset_query(); |
代码中关于date_query,可以参考官网#ticket18694中的说明
比较两种方法发现,原生语句的实现较为便捷,这主要取决于生产环境下的需求。
(完)