Let’s say you have a CPT of Events. Each event has a start date and an end date. You want to set up a View that will find Events that happen between two dates, but that doesn’t necessarily mean the start and end dates of the Events will fall between the start and end dates selected by your filters. So you need to use some date logic to determine if the event overlaps with the date range your User selects in the filters.
By default, this View will only show events beginning this current month. Any date filters selected by the User will override these defaults.
add_filter( 'wpv_filter_query', 'default_this_month_inclusive', 10, 3 ); function default_this_month_inclusive ( $query, $view_settings, $view_id ) { if( $view_id == 12345 ) { $selected_start = strtotime('0:00:00'); $selected_end = 9999999999; // determine if user has selected a start or end date, and destroy those meta query items if ( isset($query['meta_query']) ) { foreach($query['meta_query'] as $key => $meta) { if(isset($meta['key']) && $meta['key'] == 'wpcf-event-start-date'){ // get a timestamp that represents 12:00 am on the event start date $selected_start = strtotime(date('m/d/Y', $meta['value']) . ' 0:00:00'); unset($query['meta_query'][$key]); } if(isset($meta['key']) && $meta['key'] == 'wpcf-event-end-date'){ // get a timestamp that represents 11:59:59 pm on the event end date $selected_end = strtotime(date('m/d/Y', $meta['value']) . ' 23:59:59'); unset($query['meta_query'][$key]); } } } $args = array( 'relation' => 'AND', array( 'key' => 'wpcf-event-start-date', 'value' => $selected_end, 'compare' => '<=', 'type' => 'numeric' ), array( 'key' => 'wpcf-event-end-date', 'value' => $selected_start, 'compare' => '>=', 'type' => 'numeric' ) ); // add these arguments to your meta query $query['meta_query'] = isset($query['meta_query']) ? $query['meta_query'] : []; $query['meta_query'][] = $args; } return $query; }
Update your View ID and custom field slugs if necessary.