code in sidebar interrupting the main loop (3 posts)

  1. deepwhitesound
    Posted 2 years ago #

    i've inserted some code into my sidebar to bring up a list of all posts, sorted by year. the problem is that it interrupts my main loop - when clicking on both single posts as well as category links, it simply shows all posts. i understand why this is - i've started a loop in the sidebar which interferes with the main loop. here is the code i've inserted into the sidebar:

    <?php query_posts(array('nopaging' => 1, /* we want all posts, so disable paging. Order by date is default */));
    $prev_year = null;
    if ( have_posts() ) {
       while ( have_posts() ) {
          $this_year = get_the_date('Y');
          if ($prev_year != $this_year) {
              // Year boundary
              if (!is_null($prev_year)) {
                 // A list is already open, close it first
                 echo '</ul>';
              echo '<b>' . $this_year . '</b>';
              echo '<ul>';
          echo '<li><a href="'. get_permalink() .'">' . get_the_title() .'</a></li>';
          $prev_year = $this_year;
       echo '</ul>';
    } ?>

    The problem is, I don't know how to end this loop without getting a syntax error?

    Here is a link to a single post, which you can see does not return just the post but every post (so far there are only two posts):


  2. deepwhitesound
    Posted 2 years ago #

    also - if anyone knows how to alter that sidebar code so that the list it brings up EXCLUDES a certain category, could you please assist in that? I have no idea where to put the following code to make it work:


  3. paulwpxp
    Font hero
    Posted 2 years ago #

    Avoid using query_posts()

    use WP_Query instead

    and don't forget to wp_reset_postdata() at the end.

Topic Closed

This topic has been closed to new replies.

About this Topic