Categories
CMS Mastering Development Wordpress

WP_Query: Group events by year, sorted DESC; then by date for each year group, sorted ASC

I’m trying to set up a query for an “event” custom post type that groups posts by year, with a heading for each year, in descending order; then, for each year group, ordered by date in ascending order like so:

2020

  • Jan 1, 2020
  • Feb 1, 2020
  • Mar 1, 2020

2019

  • Jan 1, 2019
  • Feb 1, 2019
  • Mar 1, 2019

[and so on…]

I’m able to output the posts grouped by year using the following query and loop (I’m using Advanced Custom Fields to manage the date fields), but I’m not sure how to order each set of events in ascending order within each group? Here’s what I have thus far:

// set year heading variable for use in loop
$year_heading = '';

// set up iterator
$i = 0;

// set up query for events
$events = new WP_Query( array (
    'post_type'      => 'event',
    'post_satus'     => 'publish',
    'posts_per_page' => -1, // show all posts
    'meta_key'       => 'end_date',
    'orderby'        => 'meta_value_num',
    'order'          => 'DESC'
));

$events->query_posts();
if ($events->have_posts()) :
while ($events->have_posts()) : $events->the_post();

// get field data and format dates
$start_date = get_field('start_date');
$end_date = get_field('end_date');
$event_year = date('Y', strtotime($start_date));

// print heading for each year of events
if ($event_year != $year_heading) {
    $year_heading = $event_year;
    if ($i != 0) {
        echo '</div><!-- /.event-group -->';
    }
    echo '<h3>' . $event_year . '</h3>';
    echo '<div class="event-group">';
    // echo '<div class="event-group">';
}

// print event entries
echo '  <div class="event-item">';
echo '      <a href="' . get_the_permalink() . '">';
echo '          <h5>' . get_the_title() . '</h5>';
echo '      </a>';
echo '  </div><!-- /.event-item -->';

if ($i = 0) {
    echo '</div><!-- /.event-group -->';
}

++$i;

endwhile;
endif;

wp_reset_query();

I’m not sure if perhaps I can use pre_get_posts here in some way to modify the query? Thanks for any direction here.

Leave a Reply

Your email address will not be published. Required fields are marked *