WordPress – Loop Post Links by Year

Code swiped from http://wordpress.org/support/topic/list-all-posts-on-a-page-split-them-by-year

<?php
// Get years that have posts
$years = $wpdb->get_results( “SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = ‘post’ AND post_status = ‘publish’ GROUP BY year DESC” );

// For each year, do the following
foreach ( $years as $year ) {

// Get all posts for the year
$posts_this_year = $wpdb->get_results( “SELECT ID, post_title FROM wp_posts WHERE post_type = ‘post’ AND post_status = ‘publish’ AND YEAR(post_date) = ‘” . $year->year . “‘” );

// Display the year as a header
echo ‘<h2>’ . $year->year . ‘</h2>’;

// Start an unorder list
echo ‘</ul>’;

// For each post for that year, do the following
foreach ( $posts_this_year as $post ) {
// Display the title as a hyperlinked list item
echo ‘<li><a href=”‘ . get_permalink($post->ID) . ‘”>’ . $post->post_title . ‘</a></li>’;
}

// End the unordered list
echo ‘</ul>’;
}
?>