Problem: I have a View with two custom field filters. The first filter is applied using a shortcode attribute. The second filter is a front-end filter using a datepicker field. I can set the default date using TODAY(), but the initial result is not filtered. I would like to filter the initial results, and allow the User to change the filter as needed.
Solution:
It's possible to filter the initial result set using the default selection TODAY while still allowing front-end date filtering. Add the following code to your child theme's functions.php file, or to a new snippet in Toolset > Settings > Custom Code:
add_filter( 'wpv_filter_query', 'filter_gte_today', 10, 3 ); function filter_gte_today ( $query, $view_settings, $view_id ) { $views = array( 12345 ); $date_slug = 'wpcf-stdstartdate'; $url_param = 'wpv-wpcf-stdstartdate'; // do not edit below this line if( in_array( $view_id, $views) ) { // check to see if the datepicker filter has been manually set or manually unset // if so, bail out and don't modify it if( isset($query['meta_query'])) { $cols = array_column($query['meta_query'], 'key'); if( in_array($date_slug, $cols) || ( isset( $_GET[$url_param] ) && $_GET[$url_param] == '' )) { return $query; } } // datepicker filter has not been set or unset. Use the default value. $today = strtotime('0:00'); $args = array( 'relation' => 'AND', array( 'key' => $date_slug, 'value' => $today, '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; }
Change 12345 to match the numeric ID of this View. Change wpcf-stdstartdate to match the date field slug. You must use the 'wpcf-' prefix here. Change wpv-wpcf-stdstartdate to match the URL parameter specified in your Query filter.
Relevant Documentation:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 5 replies, has 2 voices.
Last updated by 5 years, 6 months ago.
Assisted by: Christian Cox.