WordPress相关文章:实现随机排序并筛选特定时间段内容
修改后的WordPress相关文章代码(带近3个月时间筛选)
直接在你的WP_Query参数中添加date_query即可实现时间范围筛选,以下是完整修改后的代码:
<?php $categories = wp_get_post_terms( get_queried_object_id(), 'category', ['fields' => 'ids'] ); // 计算近3个月的起始日期 $three_months_ago = date('Y-m-d', strtotime('-3 months')); $args = [ 'post__not_in' => array( get_queried_object_id() ), 'posts_per_page' => 8, 'ignore_sticky_posts' => 1, 'orderby' => 'rand', 'tax_query' => [ [ 'taxonomy' => 'category', 'terms' => $categories ] ], // 添加时间筛选条件:仅显示近3个月至今的文章 'date_query' => [ [ 'after' => $three_months_ago, 'inclusive' => true, // 包含起始日期当天的文章 ] ] ]; $my_query = new wp_query( $args ); if( $my_query->have_posts() ) { echo '<div id="related"><h4>Related Posts</h4>'; while( $my_query->have_posts() ) { $my_query->the_post(); ?> <div class="ht_grid_1_4 box-effect"> <?php if ( has_post_thumbnail() ) { ?> <a class="thumbnail-link" href="<?php the_permalink(); ?>"> <div class="thumbnail-wrap"> <?php the_post_thumbnail('justvideo_post_thumb'); ?> </div><!-- .thumbnail-wrap --> </a> <?php } ?> <div class="entry-header"> <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> </div><!-- .entry-header --> </div> <?php } wp_reset_postdata(); echo '</div><!--related-->'; } ?>
关键说明:
date_query是WP_Query内置的时间筛选参数,通过after指定起始日期,inclusive设为true确保包含起始日当天发布的文章。- 若需要调整时间范围,只需修改
strtotime('-3 months')中的数值:比如近1个月用'-1 months',半年用'-6 months'。 - 保持了原有的随机排序(
orderby' => 'rand')和分类筛选逻辑,仅新增时间过滤规则。
内容的提问来源于stack exchange,提问作者Realbro media tips
相关产品推荐
相关产品推荐

