Wordpress wp_reset_query() does not go back to las

2019-08-05 13:35发布

问题:

This is what I have:

Im editing a custom taxonomy page. On landing on the page the page query is automatically set to return a list of posts under the custom taxonomy I'm on. In that page template I run this query posts:

        query_posts(
            array_merge(
                array( 'post__in' => $_SESSION['lpoc_search_data'], 'orderby' => 'post__in' ),
                $wp_query->query
            )
        );

I run my loop and the query Ive done above works all well.

<?php while (have_posts()) : the_post(); ?>
  My Loop
<?php endwhile; ?>

But inside the above loop I do another query:

      <?php $args = array('p' => $officeID, 'post_type' => "offices"); query_posts($args); ?>
      <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
         //Inside secondary loop
      <?php endwhile; ?>
      <?php wp_reset_query(); ?>

As you can see I use wp_reset_query(); so that the loop above is returned to its original state. Or so you would think. But what is happening is that wp_reset_query() is resetting the query to the page query and not the query I did in the first code block. Why is this happening and how can I prevent this from happening?

Kind Regards

Scott

回答1:

Use get_posts() that is not touching the original query! Use setup_postdata() as in the example that you find in the codex page.

<ul>
<?php
  global $post;
  $tmp_post = $post;
  $args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
  $myposts = get_posts( $args );
  foreach( $myposts as $post ) : setup_postdata($post); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
  <?php endforeach; ?>
<?php $post = $tmp_post; ?>
</ul>