Support

Account

Home Forums Front-end Issues sort post query by ACF date picker field

Solved

sort post query by ACF date picker field

  • I’m trying to loop through my custom post type of ‘event’ that has a ‘event_start_date’ field using the Date Time Picker Field type. The return value is set to: November 22, 2021 3:11 pm : F j, Y g:i a

    I also only want to show future events and skip any event from the past. Here is what I have. This code is skipping past events as I need, but it’s not ordering them correctly.

    This is the order of the date fields as it loops through:

    November 24, 2021 8:00 pm
    December 24, 2021 8:00 pm
    November 30, 2021 11:00 pm
    January 25, 2022 1:00 pm

    here is my code for the query

    
            $today = date('Ymd');
    
            // Arguments for the query
            $args = array(
              'post_type' => 'event',
              'posts_per_page' => -1,
              'post_status' => 'publish',
              'meta_query' => array(
                array(
                  'key' => 'event_start_date',
                  'value' => $today,
                  'type' => 'DATE',
                  'compare' => '>='
                )
              ),
              'meta_key' => 'event_start_date',
              'orderby' => 'meta_value_num',
              'order' => 'ASC',
            );
    

    I have tried read through similar posts and this seems to be what is suggested, but it’s not working.

  • Does the following work:

    <?php
    $args = array(
    	
    	'post_type' => 'event',
    	'posts_per_page' => -1,
    	'post_status' => 'publish',	
    	
    	'meta_query' => array(
    		'relation' => 'AND',
    		'date_clause' => array(
               	  'key' => 'event_start_date',
                  'value' => $today,
                  'type' => 'DATE',
                  'compare' => '>='
    		),
    
    	),
    	'orderby' => array(
    		'date_clause' => 'ASC',
    	),
    );

    Code untested

  • yes that worked. Thank you!!!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.