4

Good Morning. I am having trouble comparing a timestamp returned as a meta_key (returning as a string) to the current timestamp while running get_posts().

I am trying to get any posts with end_date_time set in the future and I am getting some weird behavior. I am using Advanced Custom Fields and Advanced Custom Fields: Date and Time Picker to set the time.

Here is my code:

$time = time();

$args = array(
    'post_type'         => 'webinars',
    'posts_per_page'    => -1,
    'meta_key'          => 'date',
    'orderby'           => array('meta_value_num' => 'ASC', 'title' => 'ASC'),
    'meta_query'        => array(
        array(
            'key'   =>  'end_date_time',
            'value' =>  $time,
            'compare' => '>='
        ),
    ),
);

$webinars = get_posts($args);

The query does not return any results if it is set like this. I know that there is a post with a future timestamp set as removing the meta_query shows it and I can get the saved time stamp. (It is saved as a string).

Is there an issue with comparing strings as numbers in a meta_query? Is there a way to convert end_date_time to an int before doing the comparison?

I have also tried converting time to a string before passing it into the $args, but it does not seem to make a difference.

Has anyone else run into this issue?

Update

I have modified the $time variable to use a past time like this:

$time = time()-43200;

After doing this, the query seems to be working fine. If I set end_date_time to the future it will show in the loop, if I set it to the past it is removed from the loop. It seems that there is some sort of time discrepancy that is causing this. Without the adjusted time, events that happened two hours from now would disappear, but after the adjustment they stay displayed. When they are several hours old they still disappear as needed.

Why would this work with the adjusted timestamp $time = time()-43200;, but not with $time = time();?

Marc
  • 4,661
  • 3
  • 40
  • 62
  • 2
    Assuming that the value is in fact a timestamp (integer), then all you need to do is add this to your meta_query: `'type' => 'numeric'`. – random_user_name Jan 19 '16 at 16:56
  • When I var_dump() the value within a working loop it is returned as a timestamp that has been converted to a string. I am assuming this is how it is saved in the database. – Marc Jan 19 '16 at 17:05
  • That shouldn't matter...you're still doing a numeric comparison. – rnevius Jan 19 '16 at 17:26

1 Answers1

3

If you're using the native ACF's Date Time Picker, you should just add type DATETIME to your meta_query and be sure your value has the required format yyyy-mm-dd hh:mm:ss.

'meta_query' => array(
    array(
        'key'     => 'end_date_time',
        'value'   => date('Y-m-d H:i:s', $time),
        'compare' => '>=',
        'type'    => 'DATETIME'
    ),
),

Check Date Time Picker and WP's Meta Queries documentation.

Jordi Nebot
  • 3,355
  • 3
  • 27
  • 56