I'm currently working on a homepage for a client and when creating some custom post types i ran in to a problem. How do i add a datepicker to a WordPress meta box?

Hi everyone!

Any how, I’m currently working on a homepage for a client and when creating some custom post types i ran in to a problem. How do i add a datepicker to a WordPress meta box?

Shouldn’t be hard, there everywhere and is built in to jQuery, right? Well after a lot of googleing I was positive it was possible! But still didn’t know how. There are a couple of “do this and it’s there”-posts around but it took me going trough them all to get it.. Could be that I’m bad at understanding what people wrights or people are BAD at explaining clearly. Maybe nice to have secrets? hehe..

So to help any one out there with the same problem here is, what I hope, a clear explanation:

  1. After the function for adding stuff to the meta box add the following(it simply calls for the datepicker function in jQuery):
    // Enqueue Datepicker + jQuery UI CSS
    wp_enqueue_script( 'jquery-ui-datepicker' );
    wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css', true);
  2. After that you state the names of the fields in your meta box as usual and below that add this:
    <script>
    jQuery(document).ready(function(){
    jQuery('.cookies').datepicker({
    dateFormat : 'dd/m - yy'
    });
    });
    </script>
  3. In the script (third line where it says “.cookies”)  you state for what class or ID you want the datepicker to be added.
  4. Now add the input field and give it the class/ID you want to use, example:
    <input type="text" name="cookie_cookie_date" id="cookie" value="<?php echo $cookie_date; ?>" />
  5. And your are done and should have a datepicker in the field!

Example code:

function display_cookie_meta_box( $cookie ) {
// Enqueue Datepicker + jQuery UI CSS
wp_enqueue_script( 'jquery-ui-datepicker' );
wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css', true);

// Retrieve current date for cookie
$cookie_date = get_post_meta( $cookie->ID, 'cookie_date', true  );
?>
<script>
jQuery(document).ready(function(){
jQuery('#cookie_date').datepicker({
dateFormat : 'dd/m - yy'
});
});
</script>

<table>
<tr>
<td style="width: 100%">The cookie stays in the jar until:</td>
<td>
<input type="text" name="cookie_cookie_date" id="cookie_date" value="<?php echo $cookie_date; ?>" /></td>
</tr>
</table>
<?php
}

And it should look like this:

As you can see, wasn’t hard. Hope it was to some help!