Sort Events CPT by Custom Date Meta Field

Sort query by custom date meta to remove past events and show upcoming events in reverse chronological order.

See https://gist.github.com/mwhiteley16/09f51573cae3296ed4270ce7a7f591f0

<?php
/**
 * Filter Events CPT Using Custom Date Meta Field
 * Meta Field in this instance created via Advanced Custom Fields 
 *
 */
 
// Sort using pre_get_posts
add_action( 'pre_get_posts', 'wd_event_query_by_date' );
function wd_event_query_by_date( $query ) {
	// Check that we are on the events CPT archive, the main query and not on in the admin
	if( $query->is_main_query() && !is_admin() && $query->is_post_type_archive( 'events' ) ) {
		$meta_query = array(
			array(
				'key'     => 'wd_event_end_date', // your event meta here
				'value'   => date('Y-m-d'),
				'type'    => 'DATE',
				'compare' => '>=' // only show dates matching the current date or in the future
			)
		);
		$query->set( 'posts_per_page', -1 ); // show all posts
		$query->set( 'meta_query', $meta_query );
		$query->set( 'order', 'ASC' ); // sort showing most recent date first
		$query->set( 'orderby', 'meta_value' );
		$query->set( 'meta_key', 'wd_event_start_date' );
	}
	
}
// Sort using WP_Query
$events_query = new WP_Query(array(
	'post_type'      	  => 'events',
	'posts_per_page'	  => -1,
	'post_status'		  => 'publish',
	'meta_key'            => 'wd_event_start_date',
	'orderby'          	  => 'meta_value',
	'order'               => 'ASC',
	'meta_query'          => array(
		array(
			'key'     => 'wd_event_end_date',
			'value'   => date('Y-m-d'),
			'type'    => 'DATE',
			'compare' => '>='
		)
	),
));
if ( $events_query->have_posts() ) :
	while ( $events_query->have_posts() ) : $events_query->the_post();
		the_title();
	endwhile;
endif;

About Matt Whiteley

Matt has been building bespoke WordPress websites for over 10 years specializing in the Genesis Framework. He integrates Advanced Custom Fields heavily in all builds, especially with the new Gutenberg Block Editor, allowing clients to easily modify all aspects of the their website with ease.

He works with a wide variety of small businesses and agencies across the country providing development services as well as hosting and maintenance. When he isn't coding he enjoys spending time with his wife and two children, golfing and playing poker.