3

I am creating a custom events page and I want to know how to create a custom meta box to save event dates. I don't want it to be a regular meta box because I will be using this to make a custom search bar so I am guessing I have to save it to MySQL no?

I am lost, as to how I have to go about this. Any ideas?

Thanks in advance.

2 Answers 2

1

If you're in need of Meta Boxes for WordPress, check out the amazing code in github by jaredatch.

https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress

This allows you to add all sorts of metaboxes to your WP theme (or plugin). Date Picker, file upload, wysiwyg, text areas, text boxes...it's really amazing and saves lots of time.

1
  • 1
    Accepted answer but outdated: *This plugin is no longer supported or developed. All future development will continue on CMB2. This repo only exists for legacy reasons. This library should absolutely not be used for any new projects.
    – Ronaldt
    Oct 19, 2017 at 11:43
14

Wordpress already includes with the scripts to do datepickers.

If you dont want to do it with a plugin, create a regular text metabox, then you need to enqueue a custom script in the wordpress admin with jquery-ui and jquery-ui-datepicker dependencies:

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');

Now all we need to do is call the datepicker in our field-date js file:

jQuery(document).ready(function(){
    jQuery('.datepicker').datepicker(); 
});

Notice the .datepicker selector? replace this with an id or class for your meta box input's class/id. Then the datepicker will load once you click on the input - too easy!

6
  • Is there an easy way to use some default styling on the datepicker? I assume there's some CSS somewhere to make it look nice. Jul 27, 2017 at 4:15
  • include the cdn for datepicker ui and you are good to go!
    – Zach Smith
    Jul 27, 2017 at 19:02
  • "Wordpress comes preloaded with the scripts to do datepickers." Which are they, @rhysclay? I'd rather use something already there available in Wordpress than include a second one that has to be maintained manually.
    – Ronaldt
    Oct 19, 2017 at 11:25
  • The preloaded script is 'jquery-ui-picker', sorry maybe my choice of wording could be better, I will reupdate my answer
    – rhysclay
    Oct 19, 2017 at 12:47
  • Are there built in tools for picking a date and time (ie a timestamp)? Nov 23, 2019 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.