Using one WP_Query object within the loop of another WP_Query object

I’m creating two different WP_Query objects, one for each of two different post types I’m using. In creating my output, I’d like to loop through one of the objects, and at the same time loop through the other object as well, so I can output pieces of them together. Here’s an example of what I’d like to accomplish:

$rotator_args = array(
    'post_type' => 'rotator',
    );

$rotator = new WP_Query($rotator_args);

$numrotators = $rotator->post_count; 

$testimonial_args = array(
    'post_type' => 'testimonial',
    'posts_per_page' => $numrotators,
    );

$testimonial = new WP_Query($testimonial_args);

while ( $rotator->have_posts() ) : 
    $rotator->the_post(); //setup the rotator posts
    $testimonial->the_post(); //this breaks things, understandably
    $rotator_image = get_the_post_thumbnail($rotator->ID, 'large');
    $testimonial_image = get_the_post_thumbnail($testimonial->ID, 'large');
    $return .= '<div>' . $rotator_image . '</div>';
    $return .= '<div>' . $testimonial_image . '</div>';
endwhile;
return $return;

However, that doesn’t work. Taking out $testimonial->the_post(); (and the associated $testimonial related code) fixes things.

Related posts

Leave a Reply

4 comments

  1. I’m not sure you can merge the two loops together, since there isn’t anything to keep them separate from a data standpoint. Are you trying to add data from a testimonial into the rotator as it goes?

  2. Edit: Bill’s refactor is much better than my duct tape
    Edit: Additionally, my edit will stick with the same testimonial which wasn’t even the desired outcome. Again: please see Bill’s refactor

    The trouble you’re having is with $post. Every time you fire the_post() $post has the applicable data. I would suggest something like the following:

    global $post;
    
    $rotator_args = array(
        'post_type' => 'rotator',
        );
    
    $rotator = new WP_Query($rotator_args);
    
    $numrotators = $rotator->post_count; 
    
    $testimonial_args = array(
        'post_type' => 'testimonial',
        'posts_per_page' => $numrotators,
        );
    
    $testimonial = new WP_Query($testimonial_args);
    if( $testimonial->have_posts() )
    {
        $testimonial->the_post();
        $my_testimonial = $post;
    }
    
    while ( $rotator->have_posts() ) : 
        $rotator->the_post(); //setup the rotator posts
        $rotator_image = get_the_post_thumbnail($rotator->ID, 'large');
        $testimonial_image = get_the_post_thumbnail($my_testimonial->ID, 'large');
        $return .= '<div>' . $rotator_image . '</div>';
        $return .= '<div>' . $testimonial_image . '</div>';
    endwhile;
    return $return;
    
  3. Is there some piece of data that connects $rotator to $testimonial? If not then I don’t see what the point is…you just have two disparate loops.