How to Limit the Years Inside Your Date Picker

Introduction

Would you like to limit the years that show inside your Date Picker form field? In this tutorial, we’re going to have the Date Picker limit the year to anything that is 18 years or above. Using PHP you can easily achieve this and we’ll walk you through each step.

Creating the form

To begin, we’ll create a new form and add our fields which will include one Date field.

Once you add the Date form field, click on the Advanced tab and from the dropdown select Date Picker as the Date Type.

If you need any help in creating your form, you can review this documentation.

Setup

Next, you’ll need to copy this snippet to your site.

If you need any help in how to add snippets to your site, please check out this tutorial.

/**
 * Limit years in date picker
 *
 * @link https://wpforms.com/developers/how-to-limit-the-years-inside-your-date-picker/
 */

function wpf_dev_limit_date_picker_years() {
        ?>

        <script type="text/javascript">

                var d = new Date();
                window.wpforms_datepicker = {

                        disableMobile: true,
                        // Don't allow users to pick years less than 18 years
                        maxDate: d.setDate( d.getDate() - 6574 ),

                }

        </script>

        <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker_years', 10 );

With this snippet, we’re forcing the Date Picker to not allow the years to be anything less than 18 years.

with this snippet you can now limit years in date picker

And that’s it! You’ve now limited the years available inside your date picker. Would you like also allow for a date range in your date picker? Check out our tutorial on How to Allow Date Range or Multiple Dates in Date Picker.

Action Reference: wpforms_wp_footer_end

FAQ

Q: Can I also apply this to the Date Dropdown?

A: You can easily use a different snippet to achieve this. Simply follow this tutorial and change the year range $args['years'] = range( 2019, 2020 ); to enter the range of years you would like.