Last active
December 27, 2022 11:34
-
-
Save mwhiteley16/09f51573cae3296ed4270ce7a7f591f0 to your computer and use it in GitHub Desktop.
Sort Events by Custom Date Meta Fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you very much for the contribution.