首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Wordpress上显示前3位随机帖子

在Wordpress上显示前3位随机帖子
EN

Stack Overflow用户
提问于 2017-10-03 15:59:05
回答 1查看 67关注 0票数 0

我有自定义页面,现在有10个帖子显示,我需要显示的是第一个3随机,然后再随机4-7和8-10再次随机是他们的任何方式,我可以在then循环中管理。

代码语言:javascript
运行
复制
<?php
$count = 1;
while ( $loop->have_posts() ) : $loop->the_post();
echo the_title();
$count++;
endwhile;
?>

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-03 19:00:43

如果我对你的理解是正确的,这会让你接近你想要的。首先将您的帖子放到一个数组中:

代码语言:javascript
运行
复制
$posts = array();
while ( $loop->have_posts() ) {
    $loop->the_post();
    array_push($posts, $post);
}

然后对数组进行排序。我将用0-9演示:

代码语言:javascript
运行
复制
$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";

这将导致数组的随机排序,同时保持“块”(顶部、中部、底部)保持相同的顺序:

代码语言:javascript
运行
复制
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

把这一切结合在一起:

代码语言:javascript
运行
复制
$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,它显示了这一点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46548815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档