1

I am new to WordPress. How can I create a meta box field with date picker support?

    function enqueue_date_picker(){
        wp_enqueue_script(
            'field-date', 
            get_template_directory_uri() . '/admin/field-date.js', 
            array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker'),
            time(),
            true
        );  

        wp_enqueue_style( 'jquery-ui-datepicker' );
    }

add_action('admin_enqueue_scripts', 'enqueue_date_picker');
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
ganeshreddy
  • 33
  • 1
  • 6

2 Answers2

3

Add the following line of code to enqueue the jquery ui datepicker library from your plugin:

wp_enqueue_script('jquery-ui-datepicker');

You can download the stylesheet file from the jquery ui library site and include it in your plugin. You would then enqueue the CSS file like the following:

wp_enqueue_style('jquery-ui-css', 'http://www.example.com/your-plugin-path/css/jquery-ui.css');

Alternatively, You can include the jquery ui CSS from Google (you don’t need to ship the CSS files with your plugin if you go via this route):

wp_enqueue_style('jquery-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');

Add the following JQuery code to your javascript file so it attaches the datepicker to any fields with a class of “custom_date”:

<script type="text/javascript">
jQuery(document).ready(function($) {
$('.custom_date').datepicker({
dateFormat : 'yy-mm-dd'
});
});
</script>

Now, you can simply add class “custom_date” to the date fields in the HTML code and it will show a date picker calender when a user clicks on that field.

<input type="text" class="custom_date" name="start_date" value=""/>
devendra singh
  • 219
  • 3
  • 15
0

i have done something like this, but applying tinyMCE rich text editor to custom meta boxes. So, looking at your code, you should change:

add_action('admin_enqueue_scripts', 'enqueue_date_picker');

to

add_action('admin_print_footer_scripts', 'enqueue_date_picker');

Take care to use jQuery prefix instead $ in your JS file, if you will use the core jQuery from wordpress.

TriForce
  • 415
  • 2
  • 8