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

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了