I have a custom post type (projects) which have custom cmb2 meta keys (str_dte and end_dte), so each project has a start date and end date. What I am trying to do is to get projects between two dates.
Example:
Project #1: start date = 20120101 (Jan 2012) / end date = 20120601 (Jun 2012) (Ymd)
Project #2: start date = 20120401 (Apr 2012) / end date = 20121201 (Dec 2012) (Ymd)
The query:
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'post_type' => 'projects',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'compare' => '>=',
'value' => '20120501', //May 2012
'type' => 'DATE'
),
array(
'key' => 'end_dte',
'compare' => '<=',
'value' => '20120701', //July 2012
'type' => 'DATE'
)
),
));
Problem: this query didn't display any project, because it didn't realise the date range between the start date and end date of each project.
Shortly: I need to find a solution to query projects/posts between two dates (start date and end date) considering the date range between each project start and end date.
Online Resources: the most useful solution I have found online was (robbiegod/keesiemeijer) solution but it didn't work for me, I don't know why!
Your help is appreciated. Thank you.
SOLUTION
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'post_type' => 'projects',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'compare' => '<=',
'value' => '$end_date_value', // 20120701 July (Ymd or UnixTime)
'type' => 'DATE'
),
array(
'key' => 'end_dte',
'compare' => '>=',
'value' => '$start_date_value', // 20120501 May (Ymd or UnixTime)
'type' => 'DATE'
)
),
));
Just put the start date value result (date) as value for the end date meta key, and put the end date value result (date) as value for the start date meta key.
That's it.