I’m looking for a way to use meta_query to filter out posts with a meta-key value of a date-time in m/d/Y g:i a format.

The post-meta is being set by ACF (Advanced Custom Fields).

I want to maintain m/d/Y g:i a formatting for output on the frontend, but also need to filter out posts with dates in the past.

I know that I can use Ymd format, likeso:

$date_now = date('Y/m/d');
  $args = [
    'meta_query'=>[
      'relation'=>'AND',
      [
        'key'=>'event_time',
        'value'=>$date_now,
        'compare'=>'>=',
        'type'=>'DATE',
      ],
  ]
];

I also know that I can retrieve all posts and use a subsequent loop to discard the posts which don’t meet requirements.

But is there a better way to do this?
Thanks for reading.

1 Answer
1

There should not be any need to do this.

Even if an ACF Field is using 'return_format' => 'm/d/Y g:i a',

The post_meta value is in YYYY-MM-DD 00:00:00 format.

$date_now = date('Y-m-d');
$args = [
  'meta_key'=>'the_date',
  'meta_value'=>$date_now.' 00:00:00',
  'meta_compare'=>'>=',
];
$query = new WP_Query( $args );

Edit: I’ve noticed some discrepancies in this, the value may be in Ymd. When in doubt, check the data. You can find the post_meta by looking up the post_id in the wp_postmeta table.

Leave a Reply

Your email address will not be published. Required fields are marked *