1

I have been trying for a few days to make a homepage that displays all my posts, and after every 2 posts, a testimonial.

I have found dozens of articles describing how to count while you are in the loop and place something every 'n' number of times. Thats no problem, but what is a problem, is running Loop A, and then every 'n' number of times, placing the next item from Loop B. WP wants you to reset one loop before starting another.

So, I need to query each set separately, parse the queries, and build a new one in the order I want it before I pass to the loop. The problem is, WP_Query objects are not arrays. So i can't figure out how to do what I want. I have the whole thing worked out except for one line. I have deferred to writing the line as I would for arrays so it is evident what I am trying to do.

<?php $testimonials = new WP_Query( array('fields'=>'ids', 'post_type'=>'testimonial', 'posts_per_page' => -1)); ?>
<?php $others = new WP_Query( array('fields'=>'ids', 'post_type'=>'post', 'posts_per_page' => -1)); ?>
<?php $combined = new WP_Query() ?>

<?php $t = 0; $o = 0; ?>
<?php $total_t = $testimonials->post_count; $total_o = $others->post_count; ?>

<?php while ($total_t > $t && $total_o - 1 > $o ): ?>
    <!-- PROBLEM LINE -->
    <?php array_push($combined, $testimonials[$t], $others[$o], $others[$o+1]); ?>
    <!-- /PROBLEM LINE -->
    <?php $t++; $o = $o + 2; ?>
<?php endwhile; ?>
  • I updated my answer with what I think is a cleaner way of doing this, using the_post() over next_post(). – Cyclonecode Nov 16 '14 at 13:55
3

I'm not sure I understand the question, but if you just wan't do display something from resultset B on every nth iteration, you could use next_post() or simply call the_post() on the second query object. Of course you also need to check so there's enough items left in the result and so on:

$query1 = new WP_Query(array('post_type' => 'post'));
$query2 = new WP_Query(array('post_type' => 'page'));

// loop through each post and display the title of a page from the second query
// for every third item
while($query1->have_posts()):
  $query1->the_post();

  print get_the_title().'<br />';

  // grab a entry from our second query if we haven't reached the end yet
  if(($query1->current_post + 1) % 3 == 0 && ($query2->current_post + 1) < $query2->post_count):
    $query2->the_post();
    print get_the_title().'<br />';
  endif;

endwhile;
  • 1
    That's exactly what I needed!!! Ahhh! I was on that track yesterday. So simple it hurts. Thanks! I failed to realize you could iterate a specific query with $query->next_post(); – bennett_an Nov 16 '14 at 3:27
  • @bennett_an - Glad I could help =) – Cyclonecode Nov 16 '14 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.