Query posts between two dates (custom meta keys) CMB2

To find projects happening within a range of dates, there are 3 cases you have to account for:

  • A project starts within the range
  • A project ends within the range
  • A project starts before the range and ends after the range

You can test for these 3 cases separately with an OR meta query and 1 nested AND:

'meta_query' => array(
    'relation' => 'OR',
    array(
        'key'     => 'str_dte',
        'value'   => array( $range_start, $range_end ),
        'compare' => 'BETWEEN',
    ),
    array(
        'key'     => 'end_dte',
        'value'   => array( $range_start, $range_end ),
        'compare' => 'BETWEEN',
    ),
    array(
        'relation' => 'AND',
        array(
            'key' => 'str_dte',
            'value' => $range_start,
            'compare' => '<',
        ),
        array(
            'key' => 'end_dte',
            'value' => $range_end,
            'compare' => '>',
        ),
    ),
),

If you’re doing lots of these queries and performance is a concern, you can probably come up with a faster query manually than this will generate.

Leave a Comment