wordpress 年ごとの記事表示
やりたいこと
2018年
- 記事01
- 記事02
- 記事03
- 記事04
2017年
- 記事01
- 記事02
こんな感じ
コード
<?php $year = NULL; // 年の初期化 $first = true; // ループの一回目を判定 $args = array( 'post_type' => 'report', // 投稿タイプの指定 'orderby' => 'date', // 日付順で表示 'posts_per_page' => -1 // すべての投稿を表示 ); $the_query = new WP_Query($args); if($the_query->have_posts()){ while ($the_query->have_posts()): $the_query->the_post(); if ($year != get_the_date('Y')){ // 同じ年でなければ表示 $year = get_the_date('Y'); // 年の取得 // ループ一回目のみulの閉じタグを出力しない if ($first != true) { echo '</ul>'; echo '</div>'; } echo '<div class="year_archive_box">'; echo '<p><a href="'.home_url( '/', 'http' ).'report/'.$year.'">'.$year.'年</a></p>'; echo '<ul>'; $first = false; } // 記事タイトル等の表示 $url = esc_url(get_permalink()); $ttl = esc_html(get_the_title()); echo '<li><a href="' . $url .'" >' . $ttl . '</a></li>'; endwhile; // ループの終了 echo '</ul>'; echo '</div>'; wp_reset_postdata(); // クエリのリセット } ?>