编辑2:更新代码以说明“可能没有粘滞帖子”;)
编辑:我对帖子的数量做了一个嘘声。已修复,现在应按预期工作。
您可以通过使用两个查询来实现这一点。
<?php
//First, you get all the sticky posts
$stickies = get_option(\'sticky_posts\',array());
//then, get max 2 of them
$stickiessliced =array_slice($stickies,0,2);
$numposts = 3 - count($stickiessliced);
//$numposts is now the number of remaining "normal" posts to be queried
if(count($stickiessliced)){
//only query the stickies if there are some
$sticky_loop = array(
\'posts_per_page\' => count($stickiessliced),
\'orderby\' => \'date\',
\'post__in\' => $stickiessliced,
\'ignore_sticky_posts\' => true
);
//only get sliced sticky posts, ignore everything else
$query = new WP_Query($sticky_loop);
//do the loop for the sticky posts
if ($query->have_posts()): ?>
<?php while ($query->have_posts()): $query->the_post();?>
// loop
<?php endwhile;?>
<?php wp_reset_query();?>
<?php endif;
}
//now get the remaining posts to fill up to three
$main_loop = array(
\'posts_per_page\' => $numposts,
\'orderby\' => \'date\',
\'post__not_in\' => $stickies,
//replace $stickiessliced with $stickies to make sure that NO other stickies are queried (as is: the above queried stickies are ignored)
\'ignore_sticky_posts\' => true
);
$query = new WP_Query($main_loop);
//do the loop for the remaining posts to fill up
if ($query->have_posts()): ?>
<?php while ($query->have_posts()): $query->the_post();?>
// loop
<?php endwhile;?>
<?php wp_reset_query();?>
<?php endif;
?>
这应该是这样的:如果有0到2个粘性帖子,则会对其进行查询、循环,然后查询1到3个“正常”帖子。如果有两个以上的粘性帖子,则将前两个帖子进行切片,然后再查询一个“正常”帖子。
快乐的编码!