Taming Multiple Loops

So I’m calling a second query inside the Loop, but after the second query ends, the primary loop should take over, right?  Not in this case.

Turned out I needed to call the function wp_reset_query(); after the secondary loop.

Here was my setup: in the page.php template, I wanted a sidebar that displayed the content of another page.  The reason is some pages will need to have the same information displayed on the side, and I wanted to be able to control this on a per page basis. (There is probably a plugin for this, but programming is so much more fun.)

So in the page editor, I set up a custom meta called “sidebar-post” and set it to the path of the page I wanted to be displayed. Back in the page.php template, I set up the WP_Query call like so:

     $sidebar_post = get_post_meta($post->ID, ‘sidebar-post’, false);
     foreach ($sidebar_post as $sidebar_postitem) {
          $sidebar_querystring = ‘pagename=’.$sidebar_postitem;
          $sidebar_query = new WP_Query($sidebar_querystring);
          while ($sidebar_query->have_posts()) : $sidebar_query->the_post(); 
               the_content();
          endwhile;
     }

I set up the code so if I wanted to, I could show more than one page. Now I was able to get this page to display in the sidebar just fine, but page contents appeared again where the primary page content was supposed to be.

I tried a trick described here under the “Multiple Loops Example 2” where you set the primary query to a temporary variable, then set it back after the secondary loop.

     <?php $temp_query = $wp_query; ?>

     <!–  secondary loop processing //—>

     <?php $wp_query = $temp_query; ?>

But that didn’t work.  The secondary query was still in control.

So after some searching I found the wp_reset_query(); function which “destroys the previous query used on a custom Loop”.

So now my code looked like this:

     $sidebar_post = get_post_meta($post->ID, ‘sidebar-post’, false);
     foreach ($sidebar_post as $sidebar_postitem) {
          $sidebar_querystring = ‘pagename=’.$sidebar_postitem;
          $sidebar_query = new WP_Query($sidebar_querystring);
          while ($sidebar_query->have_posts()) : $sidebar_query->the_post(); 
               the_content();
          endwhile;
     }
     wp_reset_query();

And, just as advertised, it killed the secondary loop query and the primary content was displaying properly.

On a side note, I am planning on getting this work with both pages and posts.