PHP: Need loop to alternate between returned posts

霸气de小男生 提交于 2020-02-02 06:28:05

问题


I have a an array of posts that are returned by doing three queries. 3 posts from the blog where posts are NOT in 'In the Media' or 'Insights', 3 from the blog where posts are in 'In the Media' 3 from the blog where posts are in 'Insights'.

Here's what I have for that. I don't think it's the most elegant solution:

<? $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(); ?>

Currently, that loops through 3 homeposts, then 3 inthemedia posts, then 3 bt-insight posts.

What I need is for the loop to go through 1 homepost, 1 inthemedia post, 1 bt-insight post, then 1 homepost, 1 inthemediea post... etc repeat.

Hope that makes sense. Suggestions?


回答1:


What if you remove the allqueries stuff and after:

$insightsPosts = new WP_Query($args);

Just use this instead.

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;
}

That should just print out the title of the post and you can use the other fields as needed. This could be moved to a function to avoid duplicating the logic as well.




回答2:


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();
}


来源:https://stackoverflow.com/questions/12290933/php-need-loop-to-alternate-between-returned-posts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!