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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度