WordPress – 年別の記事一覧ページを自作する

画像のような年別の記事一覧ページの作り方について解説します。
サンプル
<?php
if(have_posts()) :
while(have_posts()) : the_post();
$year = get_the_date( 'Y' );
if($last_year !== $year){
echo "</ul>";
echo "<h2>$year</h2>";
echo "<ul>";
}
?>
<li>
<a href="<?php the_permalink();?>"><?php the_title(); ?></a>
</li>
<?php
$last_year = $year;
endwhile;
endif;
?>
上記のコードをindex.phpまたはarchive.phpなどの記事一覧ページに記述します。get_the_date()で今年の年数を取得して現在ループされている記事の年数と一致しているかを調べています。もし不一致であればループを抜け出し去年の記事一覧を出力します。