4

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
  • 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
    Commented Oct 25, 2017 at 23:29

1 Answer 1

7

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.

2
  • i wasn't aware of the ACF field value.. thought it would return, what i want it to, but that is only considered in functions, i guess. probably makes sense to always store the same value and than modify it on demand. thanks for the hint.
    – honk31
    Commented Aug 28, 2019 at 16:58
  • 1
    and instead of looking up the table, you can always get the value of a custom field wordpress style: echo '<pre>' . print_r(get_post_meta(get_the_ID(), 'FIELD_NAME'),1) . '</pre>'; aka the return value is Ymd, but Y-m-d was working fine, too.
    – honk31
    Commented Aug 28, 2019 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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