Kamal
Posted on September 6, 2022
Adding a datepicker to a WordPress admin field is a great way to improve the user experience and make data entry more efficient. There are a few steps involved in setting this up, but the end result is worth it.
In this tutorial, I will show you how you can easily create a beautiful datepicker field just like on the screenshot below without any additional JavaScript libraries.
Let’s assume that you have a text field anywhere in WordPress admin. Just add class="any-custom-class"
to it. Example:
<input type="text" class="my-datepicker" />
Now it is time to enqueue some CSS and JavaScript. You might say – “Wait, you’ve just told us that we are not going to use any JavaScript libraries!”. That’s true, but I meant additional libraries, but we can still use what is already a part of WordPress Core. It is jQuery UI.
add_action( 'admin_enqueue_scripts', 'khn_datepicker_css_and_js' );
function khn_datepicker_css_and_js() {
wp_enqueue_script( 'jquery-ui-datepicker' );
wp_enqueue_style( 'custom-css', get_stylesheet_directory_uri() . '/jquery-ui-datepicker-by-kamal.css' );
}
I’ve also added my own custom CSS for datepicker, you can find it on GitHub gist.
The last but not least, let’s initialize datepicker for every input field with the CSS class my-datepicker.
jQuery( function( $ ) {
$( '.my-datepicker' ).datepicker();
} );
If you’re looking for some customization, you can check the official documentation.
Posted on September 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.