问题
I'm building a contact form with the cf7 plugin for Wordpress. In this form I need a drop down menu which changes automatically every year. In the drop down menu I need to have the current and last 5 years in format 2020, 2019, 2018, 2017, 2016, 2015. That's easy to make with the plugin itself, but of course, when 2021 comes in, I would like that the drop down menu will changes automatically to 2021, 2020, 2019, 2018, 2017 and 2016. So that 2015 disappears(deleted).
Based on the code in this threat I tried to add the current year automatically, but unfortunately I'm already stuck. Hopefully someone can help me with this.
Thanks in advance. Best regards,
Vasco
回答1:
Usage Use in Contact Form form like this:
[select recent-years data:years]
In functions.php of your child theme, or in a custom plugin, add this function to dynamically populate the dropdown with the 5 most recent years, and get the years updated automatically as years go by:
function vasco_five_most_recent_years ($values, $options, $args) {
if ( in_array('years', $options) ){
$years = [];
$i = 0;
for( $i = 0; $i < 5; $i++){ // Get 4 most recent years after current year
$years[] = (int) date("Y") - $i;
}
return $years ;
}
return $values;
}
add_filter('wpcf7_form_tag_data_option', 'vasco_five_most_recent_years', 10, 3);
Tested, working correctly, entered in the form like so:
Rendering on frontend like so:
Based on the tutorial here https://bdwm.be/dynamically-populate-a-contact-form-7-dropdown-list-or-any-other-input-field/
来源:https://stackoverflow.com/questions/65467641/how-to-add-the-last-five-years-to-cf7-drop-down-menu