dsag14654
2017-10-03 15:59
浏览 20
已采纳

在Wordpress上显示前3个随机帖子

I have custom page where there are 10 posts showing right now, what i need to show first 3 random then next 4-7 again random and 8-10 again random Is their any way i can manage in the while loop

<?php
$count = 1;
while ( $loop->have_posts() ) : $loop->the_post();
echo the_title();
$count++;
endwhile;
?>

Thanks

图片转代码服务由CSDN问答提供 功能建议

我有自定义页面,其中有10个帖子现在显示,我需要先显示3个随机然后接下来4个 -7再次随机,8-10再次随机 他们以任何方式我可以在while循环中管理

 &lt;?php 
 $ count = 1; 
while(  $ loop-&gt; have_posts()):$ loop-&gt; the_post(); 
echo the_title(); 
 $ count ++; 
endwhile; 
?&gt; 
   
  
 

谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyuan4790 2017-10-03 19:00
    已采纳

    If I understood you correctly, this should get you close to what you want. Put your posts into an array first:

    $posts = array();
    while ( $loop->have_posts() ) {
        $loop->the_post();
        array_push($posts, $post);
    }
    

    Then sort that array. I'll demonstrate with 0-9:

    $array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    $first = array_slice($array, 0, 3);
    $second = array_slice($array, 3, 4);
    $third = array_slice($array, 7, 3);
    shuffle($first);
    shuffle($second);
    shuffle($third);
    $newarray = array_merge($first, $second, $third);
    print join(", ", $array) . "
    " . join(", ", $newarray) . "
    ";
    

    Which will lead to a random-ish sorting of the array while keeping "blocks" (top, middle, bottom) in the same order:

    0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    1, 2, 0, 6, 5, 4, 3, 8, 7, 9
    
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    0, 2, 1, 3, 4, 5, 6, 9, 8, 7
    

    Putting it all together:

    $posts = array();
    while ( $loop->have_posts() ) {
        $loop->the_post();
        array_push($posts, $post);
    }
    
    $first = array_slice($posts, 0, 3);
    $second = array_slice($posts, 3, 4);
    $third = array_slice($posts, 7, 3);
    shuffle($first);
    shuffle($second);
    shuffle($third);
    $newposts = array_merge($first, $second, $third);
    foreach($newposts as $mypost) {
        print $mypost->post_title . "<br />
    ";
    }
    

    note that I erroneously had written push $posts, $post; instead of array_push($posts, $post);, I have written a lot of Perl lately, and it shows.

    打赏 评论

相关推荐 更多相似问题