0

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
    I would try using DATETIME based on the WP_Query custom field parameters. I know it requires MySQL format (YYYY-MM-DD) for "BETWEEN" comparison but since you're asking for all those dates greater than or equal to the date given it may work. Source: codex.wordpress.org/Class_Reference/… – Tom Oct 25 '17 at 23:29
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.