我有自定义页面,现在有10个帖子显示,我需要显示的是第一个3随机,然后再随机4-7和8-10再次随机是他们的任何方式,我可以在then循环中管理。
<?php
$count = 1;
while ( $loop->have_posts() ) : $loop->the_post();
echo the_title();
$count++;
endwhile;
?>
谢谢
发布于 2017-10-03 19:00:43
如果我对你的理解是正确的,这会让你接近你想要的。首先将您的帖子放到一个数组中:
$posts = array();
while ( $loop->have_posts() ) {
$loop->the_post();
array_push($posts, $post);
}
然后对数组进行排序。我将用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) . "\n" . join(", ", $newarray) . "\n";
这将导致数组的随机排序,同时保持“块”(顶部、中部、底部)保持相同的顺序:
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
把这一切结合在一起:
$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 />\n";
}
注意,我错误地编写了push $posts, $post;
而不是array_push($posts, $post);
,我最近写了很多Perl,它显示了这一点。
https://stackoverflow.com/questions/46548815
复制相似问题