I have a page with a VIEW with a CPT called 'activities' . In the search area user can select Custom Fields: 'Month' and 'Year' from dropdown menu. I would like the 'Year' drop down menu to be filled with the <CURRENT YEAR> by default. So once user opens the page the VIEW is displaying only the activities of the current Year.
2021
2022 << active by default
2023
2024
2025
Of course user should be able to reset the filter or select any other Year manually to filter on other activities. User should also be able to select the option '- selecteer -' (which will return all Years).
The link to the page:
hidden link
Hi,
Thank you for contacting us and I'd be happy to assist.
To apply the year filter for the custom field when the page loads, you can use the "wpv_filter_query" filter:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
For example, when the ID of the view used on the "Agenda" page is "1885" and the target custom field slug is "datum-jaar", the code will look like this:
add_filter( 'wpv_filter_query', 'filter_current_year_field', 1000 , 3 );
function filter_current_year_field( $query_args, $view_settings ) {
// check if specific view
if ( (!is_admin()) && ( isset($view_settings['view_id']) ) && ($view_settings['view_id'] == 1885) ) {
// get current year
$current_year = date("Y");
// when the page loads, apply custom field filter for current year
if(empty($query_args['meta_query'])) {
$query_args['meta_query'][] = array(
'key' => 'wpcf-datum-jaar',
'value' => $current_year,
'type' => 'NUMERIC',
'compare' => '=',
);
$_GET['wpv-wpcf-datum-jaar'] = $current_year;
}
}
return $query_args;
}
The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.
Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/
regards,
Waqar
My issue is resolved now. Thank you!
Function works exactly as intended.
Kind regards, Fred