Skip to content

Instantly share code, notes, and snippets.

@mwhiteley16
Last active December 27, 2022 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mwhiteley16/09f51573cae3296ed4270ce7a7f591f0 to your computer and use it in GitHub Desktop.
Save mwhiteley16/09f51573cae3296ed4270ce7a7f591f0 to your computer and use it in GitHub Desktop.
Sort Events by Custom Date Meta Fields
<?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;
@hosnicolina
Copy link

thank you very much for the contribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment