繁体   English   中英

PHP:需要循环才能在返回的帖子之间切换

[英]PHP: Need loop to alternate between returned posts

我有一个由三个查询返回的帖子数组。 来自博客的3个帖子中的帖子不在“媒体”或“洞察”中,3个来自博客的帖子在“媒体”3中来自博客的帖子在“洞察”中。

这就是我所拥有的。 我不认为这是最优雅的解决方案:

<? $args = array(
    'post_type' => 'post',
    'posts_per_page' => 3,
    'category__not_in' => array( 268, 269 )
  );
$homePosts = new WP_Query($args);

$args = array(
    'post_type' => 'post',
    'category_name' => 'in-the-media',
    'posts_per_page' => 3
  );
$inthemediaPosts = new WP_Query($args);

$args = array(
  'post_type' => 'post',
  'category_name' => 'bt-insights',
  'posts_per_page' => 3
);
$insightsPosts = new WP_Query($args);

$allqueries = array($homePosts,$inthemediaPosts,$insightsPosts);
foreach ($allqueries as $myquery) {
  while ($myquery->have_posts()) : $myquery->the_post(); ?>

目前,循环通过3个主页,然后是3个媒体帖子,然后是3个bt-insight帖子。

我需要的是循环通过1个主页,1个媒体帖子,1个bt-insight帖子,然后1个homepost,1个inthemediea post ...等重复。

希望有道理。 建议?

while($allqueries[0]->have_posts() || $allqueries[1]->have_posts() || $allqueries[2]->have_posts()) {
  if ($allqueries[0]->have_posts()) $allqueries[0]->the_post();
  if ($allqueries[1]->have_posts()) $allqueries[1]->the_post();
  if ($allqueries[2]->have_posts()) $allqueries[2]->the_post();
}

如果你删除allqueries的东西,之后怎么办:

$insightsPosts = new WP_Query($args);

只需使用它。

for ($i = 0; $i < 3; $i++) {
    if ($homePosts->post_count > $i)
        echo $homePosts->posts[$i]->post_title;
    if ($inthemediaPosts->post_count > $i) 
        echo $inthemediaPosts->posts[$i]->post_title;
    if ($insightsPosts->post_count > $i) 
        echo $insightsPosts->posts[$i]->post_title;
}

这应该打印出帖子的标题,你可以根据需要使用其他字段。 这可以移动到一个函数,以避免重复逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM