As being a WordPress developer, We are taking daily challenges while developing.  Sometimes we need to use WordPress Datepicker in the theme or plugin. To add a datepicker in the WordPress theme, plugin, and template simply use the below steps.

Step 1: Initialise Script and CSS

Please copy the below code and paste it into functions.php file. You can paste in your requirement file also.

<?php
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
?>

Step 2: Create an HTML

Next, add a text box where you want to display datepicker in the HTML in the file. You can change the ID and NAME as per your requirement. If you want to change these, then make sure that you have changed them in the remaining code also.

<input type="text" id="MyDate" name="MyDate" value=""/>

Step 3: Put Scripts in Files

The next step is to use the scripts in the header or footer. There are many ways to put the scripts in the header or footer. You can use any of them which are mentioned here.

The direct script in header.php or footer.php file.

Copy the below script and placed it in the header.php or footer.php file. Please do the needful if you know the WordPress theme structure.

<script>
jQuery(document).ready(function() {
 jQuery('#MyDate').datepicker({
 dateFormat : 'dd-mm-yy'
 });
});
</script>

Using WordPress Action hooks

With the help of action hooks, we can place the scripts in the header.php and footer.php files. Copy the below code and place in the functions.php file to display the datepicker scripts

Header

If you want to put the script in the header.php then use the below code.

<?php
function my_datepicker_script() {
?>
   <script>
        jQuery(document).ready(function() {
	     jQuery('#MyDate').datepicker({
	        dateFormat : 'dd-mm-yy'
	     });
	});
    </script>
    <?php
}
add_action('wp_head', 'my_datepicker_script');

 

Footer

If you want to put the script in the footer.php then use the below code.

<?php
function my_datepicker_script() {
    ?>
    <script>
		jQuery(document).ready(function() {
		 jQuery('#MyDate').datepicker({
		 dateFormat : 'dd-mm-yy'
		 });
		});
	</script>
    <?php
}
add_action( 'wp_footer', 'my_datepicker_script' );
?>

Please note again, in the above script replace your id with MyDate. I have used the date format to dd-mm-yy. You can use another format if you want.

Please do let me know if you have any queries and let us know your thoughts via a comment.