Custom post type archive sorted and grouped by date in post meta field

OK, so this problem has two parts:

  1. Make WordPress to sort these posts properly.
  2. Make WordPress to display them with all that grouping.

1. Sorting CPT by meta value on archive

You can use pre_get_posts to achieve this.

add_action( 'pre_get_posts', function ( $query ) {
    if ( is_post_type_archive( 'event' ) && $query->is_main_query() ) {
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
        $query->set( 'meta_key', 'event_startdate' );
    }
} );

So now events will be sorted ascending by start_date.

2. Displaying and grouping

You’ll have to modify the archive-event.php file, so these events get in their groups.

<?php
    $current_year = $current_month="";

    while ( have_posts() ) :
        the_post();

        $last_year = $current_year;
        $last_month = $current_month;

        $current_year = date( 'Y', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );
        if ( $last_year != $current_year ) {
            $last_month="";
        }
        $current_month = date( 'F', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );
?>
    <?php if ( $last_year != $current_year ) : ?><h2><?php echo $current_year; ?></h2><?php endif; ?>
    <?php if ( $last_month != $current_month ) : ?><h3><?php echo $current_month; ?></h3><?php endif; ?>
    <a href="https://wordpress.stackexchange.com/questions/329007/<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>

Leave a Comment