Year Headings in Blog and Archive Lists
Inserts a year heading such as "2024" between posts whenever the year changes on blog and archive pages, making long date-ordered lists easier to scan.
Opens WPIDE on
Code
// Heading level used for the year dividers.
$wpide_year_heading_tag = 'h2';
add_action( 'the_post', function ( $post, $query ) use ( $wpide_year_heading_tag ) {
static $last = null;
// Classic themes only; lists in date order only (blog, category, tag and other archives).
if ( wp_is_block_theme() || is_admin() || ! $query->is_main_query() || ! ( $query->is_home() || $query->is_archive() ) || $query->is_year() || ! in_array( $query->get( 'orderby' ), array( '', 'date', 'post_date' ), true ) || ! in_the_loop() ) {
return;
}
$year = get_the_date( 'Y', $post );
if ( $year === $last ) {
return;
}
// No divider above the first post on the first page when it is from the current year.
$show = null !== $last || $query->is_paged() || wp_date( 'Y' ) !== $year;
$last = $year;
if ( $show ) {
$tag = in_array( $wpide_year_heading_tag, array( 'h2', 'h3', 'h4', 'p' ), true ) ? $wpide_year_heading_tag : 'h2';
echo '<' . $tag . ' class="wpide-year-divider" style="margin:2em 0 1em;padding-bottom:.25em;border-bottom:1px solid rgba(127,127,127,.35);font-size:1.25em;">' . esc_html( $year ) . '</' . $tag . '>'; // phpcs:ignore WordPress.Security.EscapeOutput -- tag from a fixed list.
}
}, 10, 2 );
Notes
For classic themes; lists sorted by something other than date get no headings.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.