Skip to content

Instantly share code, notes, and snippets.

@benpearson
Last active August 15, 2017 06:53
Show Gist options
  • Save benpearson/63698a003d103a4532f9e17b1e2e3b3d to your computer and use it in GitHub Desktop.
Save benpearson/63698a003d103a4532f9e17b1e2e3b3d to your computer and use it in GitHub Desktop.
ACF Date Time Picker field: sorting and filtering posts based on the data
<?php
/**
* Events custom post type has an ACF "end_date_time" which is a Date Time Picker field.
* This code creates list of all events that have not yet ended, sorted with
* the events that are ending soonest at the top of the list.
*/
$now_date_time = new DateTime( 'now', new DateTimeZone( 'Australia/Melbourne' ) );
$upcoming_events = [];
$events_query_args = array(
'post_type' => 'event',
'posts_per_page'=> -1
);
$events_query = new WP_Query( $events_query_args );
$event_posts = $events_query->posts;
// Save all events that haven't ended into an array
foreach ( $event_posts as $event_post ) {
// Get event end date and time from ACF and create DateTime object
/**
* NOTE
* The default return format for the ACF Date Time Picker
* field ("d/m/Y g:i a") is not compatible with PHP's DateTime class.
* Use the return format "Y-m-d H:i:s"
*/
$end_date_time_str = get_field( 'end_date_time', $event_post->ID );
$end_date_time_obj = new DateTime( $end_date_time_str );
// If event has not ended yet
if ( $now_date_time <= $end_date_time_obj ) {
// Add end date and time ACF data to post object
$event_post->end_date_time_str = $end_date_time_str;
// Save post object to array of upcoming events
$upcoming_events[] = $event_post;
}
}
// Sort events so that the events ending soonest are first in the array
usort( $upcoming_events, function( $a, $b ) {
$a_date_time = new DateTime( $a->end_date_time_str );
$b_date_time = new DateTime( $b->end_date_time_str );
if ( $a_date_time == $b_date_time ) {
return 0;
}
return $a_date_time < $b_date_time ? -1 : 1;
});
?>
<ul class="upcoming-events">
<?php foreach( $upcoming_events as $event ) : ?>
<li>
<a href="<?php echo get_the_permalink( $event->ID ); ?>"><?php echo get_the_title( $event->ID ); ?></a>
</li>
<?php endforeach; ?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment