Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

this is in my sidebar.php file, which is pulled in in the header.php file (is this bad practice?). anyways, the last item in the list is the current page title, despite my query_posts with an args of only the custom post type of newsletters

<?php 
  if (function_exists('dynamic_sidebar') && dynamic_sidebar('Sidebar Widget')) : else : ?>
<div id="sidebar" class="newsletters">
  <h2>Newsletters</h2>
  <ul>
  <?php 
    $args = array ('post_type' => 'newsletters');
    query_posts($args);
    if (have_posts()) : while (have_posts()) : the_post();?>
      <li><a href="<?php the_field('pdf');?>"><?php the_title();?></a></li> 
      <?php wp_reset_query(); endwhile; endif; ?>
    </ul>
</div><!--END sidebar -->
share|improve this question
add comment

1 Answer 1

up vote 2 down vote accepted

Simple answer - because you're using query_posts(), which alters the main query. It almost always produces unintended results, as you're finding out the hard way right now.

Generally, it's best to call the sidebar using get_sidebar() instead of include (which you probably are, but it's not clear), and I prefer to call it after the main loop has run so I can use a new WP_Query() instead. This will replace the current loop with completely fresh data, and would be my choice of solution. Replace query_posts($args) with $query = new WP_Query($args) and you should be good to go. Normally, I'd say get rid of your wp_reset_query() as well, but since you're calling this in the header you have to leave it so it gives you the normal page data for the rest of the page. This will lead to some overhead, but if you have good caching you shouldn't notice it at all.

Edit

Example "working" code:

<?php 
if (function_exists('dynamic_sidebar') && dynamic_sidebar('Sidebar Widget')) : else : ?>
  <div id="sidebar" class="newsletters">
    <h2>Newsletters</h2>
    <ul>
    <?php 
      $args = array ('post_type' => 'newsletters');
      $query = new WP_Query($args);
      while ( $query->have_posts() ) : $query->the_post();

        $pdf=get_field('pdf');
        echo "<li>";
        echo '<a href="'.$pdf.'">';
        the_title();
        echo "</a></li>";   

      endwhile; wp_reset_postdata(); ?>

    </ul>
</div><!--END sidebar -->
<?php endif; ?>
share|improve this answer
    
yeah, im pulling the sidebar in with get_sidebar(); but it's in the header final code below: –  Kegan Quimby May 24 '12 at 14:52
1  
If using WP_Query() for the secondary loop, you should omit wp_reset_query(), and call wp_reset_postdata() instead. –  Chip Bennett May 24 '12 at 15:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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