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;