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.
Go through each loop, storing the post object in an array. Then at the end combine them. (This is completely untested)
https://gist.github.com/1762204
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?
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:
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.