I want to display posts links from a category group by year. Group by year becouse by default wordpress repeat the date for each post. I try use a code but I got all post in current year. How can I do it?
Example I want to do:

2010

  • post link 20
  • post link 19
  • post link 18
  • post link 8

2009

  • post link 7
  • post link 6

The code:

<?php
query_posts(array('nopaging' => 1, /* desabilitar a paginacao pata obter todos os pots. O padrao e ordenado pela data */));
$prev_year = null;

query_posts('cat=27');

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 '<h2 class="titulo-conteudo">'. $this_year . '</h2>';
   echo '<div class="barra-amarela-4"></div>';
              echo '<ul>';
          }
      echo '<li>';

      // Imprimi o link do post.
  the_post(); ?>

                <div class="entry">
  <h2 id="post-<?php the_ID(); ?>">
  <a href="https://wordpress.stackexchange.com/questions/1656/<?php the_permalink(the_title()) ?>"><?php the_title(); ?></a></h2>


  </div>  

<?php 

      echo '</li>';
      $prev_year = $this_year;

   }
   echo '</ul>';

}

?>

4 Answers
4

I wrote that original code on Stack Overflow, but I didn’t see your further replies because you posted them as answers and not as comments to my answer. I have tested the code now with a specific category and it works for me, but it needs one crucial change: the call to the_post() (which I completely forgot) must come right at the beginning of the while ( have_posts() ) loop, otherwise the year will always lag one post behind. I have corrected that in the original answer.

If you want to specify multiple criteria for your query, you must combine them in the same function call. So not query_posts('cat=27'); query_posts('nopaging=1');, but query_posts('cat=27&nopaging=1'). You can also use the array format (as in my original example), I prefer that for readability.

A last change: if this is not the main loop of your page (and I suspect this code will end up in a sidebar, so not the main loop), [it is better not to use query_posts()][2]. Instead, try get_posts() and use the result of that. I did not know this when I wrote the original answer, but hanging around on this site learns you a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *