I have a custom post type called Events, with 2 custom fields, start date and end date. These fields are stored using a timestamp in the database. I want to create a custom query based on these 2 values, so i can list events that are inside the specified date/time range. This is how my code looks like:
$start_date = strtotime($_POST['start_date']);
$end_date = strtotime($_POST['end_date']);
$args = array(
'post_type' => 'event',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query'=>array(
'relation'=>'AND',
array(
'key' => 'event_start_date',
'value' => $start_date,
'compare' => '<=',
'type' => 'NUMERIC'
),
array(
'key' => 'event_end_date',
'value' => $end_date,
'compare' => '>=',
'type' => 'NUMERIC'
)
)
);
$events = new WP_Query($args);
So i’m using a simple NUMERIC meta_query, since all of my values and keys stored in a timestamp. The code looks fine for me, but somehow theres no results in this query. Here is an example:
$star_date = 1343779200
$end_date = 1412121600
And one of my event post has these values as a custom field:
event_start_date = 1375315200
event_end_date = 1377734400
So it should give me at least one result, because the start_date is smaller and the end_date is higher compared to the event_start_date and event_end_date.
Any idea whats wrong?
I think you have used wrong comparison operators in meta query .It should be >= for ‘event_start_date’ and <= for ‘event_end_date’ .