Display posts in blocks of years?

WordPress 2 posts 2 voices

  1. Is it possible to display a list of posts and wrap them in a container for a particular year or even a month if need be.

    A bit like how this site works..


    So a title of the year, then that years posts… stop.
    Older year title, then that years posts..

  2. Assuming you just have a basic posts loop (ordered by date), you’d only need something like this:

    <?php $current_year = ''; ?>
    <?php while ( have_posts() ) : the_post(); ?>
    	<?php $year = get_the_time( 'Y' ); ?>
    	<?php if ( $current_year !== $year ) {
    		$current_year = $year; ?>
    		<h2 class="year-header"><?php echo $year; ?></h2>
    	<?php } ?>
    	Output your post stuff here.
    <?php endwhile; ?>