MENU

WordPress の年別アーカイブを年度別(4月はじまり)にカスタマイズする方法。

Google先生に聞いたらすぐ出てくると思ったけど、なかなかうまく情報が拾えず、自前でゴニョゴニョする必要があったので備忘録的メモ。

学校や役所がらみだと、年別アーカイブを年度別(4月1日はじまり3月末締め)で情報を出す必要がある場合あり。
というか、あった。

まずは、pre_get_postsで、ループ前に変更。

function custom__pre_get_posts( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return $query;
    }

    if ( is_year() ) {
        $y = get_query_var( 'year' );
        $date_from = $y . '-04-01';
        $date_to = ( $y + 1 ) . '-03-31 23:59:59';
        $query->set( 'date_query', array(
            'compare' => 'BETWEEN',
            'after' => $date_from,
            'before' => $date_to,
            'inclusive' => true,
        ) );
        $query->set( 'year', null ); //元々あった年指定を削除
    }
    return $query;
}
add_action( 'pre_get_posts', 'custom__pre_get_posts' );

これでOK。