Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.