How to add the last five years to cf7 drop down menu?

心已入冬 提交于 2021-01-29 09:00:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!