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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)