我想做的是:
如果在过去7天内有人在“特色”类别中添加了帖子,请在循环中显示。否则,显示最近七天评论最多的帖子。
到目前为止,我可以显示评论最多的帖子,但我不确定如何设置if/else块,或者wordpress核心是否有内置功能。
<?php
// retrieve posts from the last seven days
function filter_where( $where = \'\' ) {
// posts in the last 7 days
$where .= " AND post_date > \'" . date(\'Y-m-d\', strtotime(\'-7 days\')) . "\'";
return $where;
}
$args = array(
\'posts_per_page\' => 1,
\'orderby\' => \'comment_count\'
);
add_filter( \'posts_where\', \'filter_where\' );
$the_query = new WP_Query( $args );
remove_filter( \'posts_where\', \'filter_where\' );
?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $do_not_duplicate = $post->ID; ?>
<a href="<?php the_permalink();?>"><h1 class="main-heading"><?php the_title(); ?></h1></a>
<p class="meta">Published on <?php the_date(); ?> by <a href="<?php echo the_permalink();?>"><?php the_author(); ?></a><a href="<?php the_permalink();?>"> <?php comments_number(); ?></a></p>
<?php the_excerpt(); ?>
<hr>
<?php endwhile; else: ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
最合适的回答,由SO网友:birgire 整理而成
您可以通过使用date_query
属于WP_Query()
, 而不是posts_where
滤器
然后可以尝试以下操作(未测试):
// Fetch from the \'featured\' category
$args = array(
\'posts_per_page\' => 1,
\'category_name\' => \'featured\',
\'date_query\' => array( array( \'after\' => \'1 week ago\' ) ),
);
$the_query = new WP_Query( $args );
if ( 0 === $the_query->found_posts )
{
// Fetch the most commented post
$args = array(
\'posts_per_page\' => 1,
\'orderby\' => \'comment_count\',
);
$the_query = new WP_Query( $args );
}
// Your loop here:
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ) : $the_query->the_post();
// ...
endwhile;
wp_reset_postdata();
else:
_e( \'No posts found!\' );
endif;
希望这有帮助。