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

时间:2017-10-03 15:59:05

标签: php wordpress

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

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

由于

1 个答案:

答案 0 :(得分:1)

如果我理解正确,这应该让你接近你想要的。 首先将你的帖子放入一个数组:

$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";

这将导致数组的随机排序,同时保持&#34;块&#34; (顶部,中部,底部)顺序相同:

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,它显示了。

相关问题