如何显示最大。当POSTS_PER_PAGE为3时发布2个粘滞帖子?

时间:2018-10-02 作者:Damian

我对粘贴帖子有问题。这是我的循环:

<?php
$main_loop = array(
    \'posts_per_page\' => 3,
    \'orderby\' => \'date\',
);
$query = new WP_Query($main_loop);
?>
     <?php if ($query->have_posts()): ?>
     <?php while ($query->have_posts()): $query->the_post();?>

// loop

     <?php endwhile;?>
     <?php wp_reset_query();?>
     <?php endif;?>
现在,当posts\\u per\\u page为3时,我需要显示最多2篇粘性帖子。因此:

当1粘性时,也有2个常规帖子,当2粘性时,也有1个常规帖子,当0粘性时,有3个常规帖子。

我该怎么做?

1 个回复
最合适的回答,由SO网友:HU ist Sebastian 整理而成

编辑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个“正常”帖子。如果有两个以上的粘性帖子,则将前两个帖子进行切片,然后再查询一个“正常”帖子。

快乐的编码!

结束