Hello!
I need to filter results of a view with dates related to custom fields.
Filter based in current day. Custom field is dia-actiu and this custom field is a date (no time). Filter is -> Select items with field: Dia actiu del menu is a number equal to TODAY() . This doesn't work
I have another view with other filter based in a range days. Custom fields are date (no time). Filter is -> Select items with field: Data final de vigencia del menu is a number lower than or equal FUTURE_DAY(-1) AND Data de vigencia del menu is a number greater than or equal TODAY() .
Data final de vigencia del menu is the end day
Data de vigencia del menu is start day.
How can I setup the date filter. I tried several options without result.
I read
https://toolset.com/documentation/user-guides/views/date-filters/
https://toolset.com/forums/topic/a-query-filter-which-checks-if-todays-date-is-between-2-custom-field-dates/
Thanks in advanced
Minesh
Supporter
Languages:
English (English )
Timezone:
Asia/Kolkata (GMT+05:30)
Hello. Thank you for contacting the Toolset support.
To filter the view by current date requires to use the view's filter: wpv_filter_query
Can you please try to add the following filter code to "Custom Code" section offered by Toolset:
=> https://toolset.com/documentation/programmer-reference/adding-custom-code/using-toolset-to-add-custom-code/#adding-custom-php-code-using-toolset
add_filter( 'wpv_filter_query', 'default_today_inclusive', 10, 3 );
function default_today_inclusive ( $query, $view_settings, $view_id ) {
if( $view_id == 99999) {
// defaults
$selected_start = strtotime('0:00:00');
$selected_end = strtotime('23:59:59');
// if user selected a start date, update the default selected values accordingly, and unset existing start meta query
if ( isset($query['meta_query']) ) {
foreach($query['meta_query'] as $key => $meta) {
if(isset($meta['key']) && $meta['key'] == 'wpcf-datefield'){ /// replace "datefield" with your original field slug
$selected_start = strtotime(date('m/d/Y', $meta['value']) . ' 0:00:00');
$selected_end = strtotime(date('m/d/Y', $meta['value']) . ' 23:59:59');
unset($query['meta_query'][$key]);
}
}
}
// find events with start date less than or equal to selected date
// and end date greater than or equal to selected date
$args = array(
'relation' => 'AND',
array(
'key' => 'wpcf-datefield',
'value' => $selected_end,
'compare' => '<=',
'type' => 'numeric'
),
array(
'key' => 'wpcf-datefield',
'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;
}
Where:
- Replace 99999 with your original view ID
- Replace datefield with your original custom date field slug
More info:
=> https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
My issue is resolved now. Thank you!