Adding jQuery datepicker to a WordPress form

Do you need to add a jQuery datepicker to your custom form in WordPress? It’s very easy, as jquery-ui-datepicker is already embedded in WordPress.

This is what we want to accomplish: a form with an input field that shows a datepicker when clicked.

First, let’s build a simple form for the date input field and the submit button. Note the class=”datepicker” – the class will be used by jQuery to know on what field to show the calendar:

 
[gist id=”755a309fa8bae87923cc7162314135c8″]

Next, we need to enable the jquery-ui-datepicker script and css. Open the functions.php and locate the add_action( ‘wp_enqueue_scripts’) function where we need to add the script and the css. Just in case you don’t have the wp_enqueue_scripts function, here is a sample:

[gist id=”fe2eeee7357ef5fe75a1fc5a68131a6d”]

You need to do 2 things:

  • wp_enqueue_script(‘jquery-ui-datepicker’) – this will enable the datepicker UI
  • Enqueue the jQuery UI theme css file from google

Next we need to add the jQuery script that will add the datepicker functionality to the class=”datepicker” input field:

[gist id=”21188920536050bf592fd0117eebb94f”]