Events Grouped by Event Year

In this Pro tutorial, we share the PHP code for outputting past events grouped by the event year in descending order of the event year.

Scenario:

CPT: event
Date custom field: event_date

Sample events:

Current date at the time of writing this tutorial: 5 Apr 2023

Output:

We shall

  • get all the past events using get_posts() and a meta_query
  • loop through the past events and store them as values of an array whose keys are the years
  • sort years in descending order
  • loop through the years and output the events grouped by years

Note: This code can be used in any WordPress site and is not Bricks-specific.

PHP

<?php

// get past events
$posts = get_posts( [
    'post_type' => 'event',
    'posts_per_page' => 100, // set this to a large enough number
    'meta_query' => [
        [
            'key' => 'event_date',
            'value' => date( 'Ymd' ),
            'compare' => '<',
            'type' => 'DATE',
        ],
    ],
] );

// if no past events, return
if ( empty( $posts ) ) {
    return;
}

// array to store past events' years
$years = [];

// loop through past events and store them as values of an array whose keys are the years
foreach ( $posts as $post ) {
    $event_date = get_post_meta( $post->ID, 'event_date', true );

    $year = date( 'Y', strtotime( $event_date ) );

    $years[ $year ][] = $post;
}

// sort years in descending order
krsort( $years );

echo '<div class="past-events__event-years">';
    // output past events grouped by years
    foreach ( $years as $year => $posts ) {
        echo '<div class="past-events__event-year">';
            echo '<h3 class="past-events__year">' . $year . '</h3>';

            echo '<div class="past-events__events">';
                foreach ( $posts as $post ) {
                    echo '<div class="past-events__event">';
                        // linked title
                        printf( '<h3 class="past-events__event-title"><a href="%s">%s</a></h3>', get_permalink( $post->ID ), $post->post_title );
                        
                        // printf event date
                        $event_date = get_post_meta( $post->ID, 'event_date', true );
                        printf( '<p class="past-events__event-date">%s</p>', date( 'F j, Y', strtotime( $event_date ) ) );
                    echo '</div>';
                }
            echo '</div>';
        echo '</div>';
    }
echo '</div>';

?>

CSS

.past-events__event-years {
  display: flex;
  flex-direction: column;
  gap: 2em;
}

.past-events__year {
  margin-bottom: 0.75em;
}

.past-events__events {
  display: flex;
  flex-direction: column;
  gap: 1em;
  margin-left: 1.5em;
}

.past-events__event-title {
  margin-bottom: 0.2em;
}