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();
?
If you’re using the native ACF’s Date Time Picker, you should just add type
DATETIME
to yourmeta_query
and be sure yourvalue
has the required formatyyyy-mm-dd hh:mm:ss
.Check Date Time Picker and WP’s Meta Queries documentation.