Using the Advanced Custom Fields Date Picker for Ordering Posts and Displaying the Date

How to use the date picker with Advanced Custom Fields to order your posts and show the date. With this example you can show the start date and if it’s a multiple day event, it will show the end date if you have one. It will also not show expired dates.

First, add two Custom Fields to your posts called, Start Date (start_date) and End Date (end_date).

Fill out a couple test posts. Some with just a start date and some with a start and end date.

Here’s the code:

<?php

// get the current date from your computer
$thedate = date("Ymd"); 

// arguments for our events list
$args = array(
	'post_type' => 'courses', // custom post type
	'posts_per_page' => -1, // show all
	'meta_key' => 'start_date', // Date picker Custom Field "start_date"
    'meta_value' => $thedate, // set a value to compare your date with
    'meta_compare' => '>', // Greater than
    'orderby' => 'meta_value', // order by date
    'order' => 'ASC' // Order Ascending 
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>

<div class="events">
        
<?php  while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<?php 
		// Set some variables to set how to show the dates.
		$startdate = DateTime::createFromFormat('Ymd', get_field('start_date'));
		$enddate = DateTime::createFromFormat('Ymd', get_field('end_date'));  ?>

<h2><?php the_title(); ?></h2>

<div class="eventdate">
<?php   // echo the startdate variable we set from above
		echo $startdate->format('M d'); ?>
<?php  
		// if there is an enddate, echo a dash and the enddate
		if(get_field('end_date')!="") { echo " " . "-" . " " . $enddate->format('M d'); } ?>
</div><!-- start date -->

<?php endwhile; ?>
</div><!-- events -->
<?php endif;  // end query courses ?>