I am having difficulty filtering date values using WP_Query and meta values that are dates. I have a custom post type and meta values for each post, two of the meta values are dates: event_start_date
and event_end_date
. My front-end code is working great until I require the query to only show posts where event_start_date >= today
I have 5 custom posts that I'm testing with, event_start_date values are below (each has the meta values stored as DateTime objects in the DB which I've edited below for sake of readability) :
- 2012-04-03
- 2012-04-10
- 2012-04-11
- 2012-04-17
- 2017-03-29
What is currently being displayed is all posts (matching the custom post type) irrespective of the date of the post. My code below is adapted from this Codex Link on WP_Query and using the rules from this Codex Link on meta_query:
$args = array(
'post_type' => 'event' ,
'posts_per_page' => $numberOfPosts, //declared variable
'meta_key' => 'event_start_date',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'event_start_date',
'value' => '2017-01-01', //I've hard-coded this to test with
'compare' => '>=',
),
)
);
$listings = new WP_Query( $args );
I considered that my compare operator could be the wrong way around, so I tried "<=" when I do this I get "No listing found" error.
Edit
After implementing the helpful answer below, the problem persisted, it turns out that the meta_query doesn't like the date being stored as an object. I updated how my meta_values were stored and tested again and all works.