Problem: I have a custom field that holds date-like values in the format YYYY-MM. I would like to add a Query Filter to my View based on this custom field, and set it up so that the results are from the current year and the previous two years.
Solution: Use the wpv_filter_query PHP filter to find date fields "like" the 3 most recent years:
// Filter a View by date-like custom field value YYYY-MM, show only results from current year and two previous years
// https://toolset.com/forums/topic/view-which-filters-on-yyyy-mm/
add_filter( 'wpv_filter_query', 'tssupp_yyyy_mm_two_years_ago', 99, 3 );
function tssupp_yyyy_mm_two_years_ago( $query_args, $views_settings, $view_id) {
$view_ids = array( 123 ); // your view ID or IDs
$date_field_slug = 'field-slug'; // your date field slug
// --------- you should not edit below this line ---------------------
if (in_array($view_id, $view_ids)){
$year = date('Y');
$query_args['meta_query'] = array(
'relation' => 'OR',
'year1_clause' => array(
'key' => 'wpcf-'.$date_field_slug,
'compare' => 'LIKE',
'type' => 'STRING',
'value' => $year
),
'year2_clause' => array(
'key' => 'wpcf-'.$date_field_slug,
'compare' => 'LIKE',
'type' => 'STRING',
'value' => ($year-1)
),
'year3_clause' => array(
'key' => 'wpcf-'.$date_field_slug,
'compare' => 'LIKE',
'type' => 'STRING',
'value' => ($year-2)
)
);
}
return $query_args;
}
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 6 replies, has 2 voices.
Last updated by 4 years, 8 months ago.
Assisted by: Christian Cox.