Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple dates to custom post type in Wordpress

I am building a Wordpress site with pages, posts and events (with multiple dates you can sign in). I am new to Wordpress so I was looking for ideal solution for this events.

I believe the best solution is to create custom post type called "Event" and then handle it separately.

I am not sure however how to add multiple dates to each event. I have been reading about custom taxonomies and post metadata but every example I went through was like creating a custom category, tag or adding a single value to the post.

What would you recommend for adding multiple dates (dont know how many in advance) to a custom post type? Is it taxonomy or post metadata? Is there a metadata of type date with build-in date input validation or datepicker?

Thank you!

like image 882
Macejkou Avatar asked Dec 12 '25 19:12

Macejkou


1 Answers

Steps to Achieve this:

  1. Add Meta Box
  2. Add Multiselect Datepicker
  3. Save Meta Value
  4. Get Meta Value

Now, In Detail

Add Meta Box & Add Multi Select Datepicker

Add Meta Box & Set Multi Select Datepicker in its HTML. Use jQuery date picker multi select and unselect to add multi select date picker.

function myplugin_add_meta_box() {

    add_meta_box(
        'event-date',
        'Set Event Dates',
        'myplugin_meta_box_callback',
        'event'
    );
}
function myplugin_meta_box_callback(){
    // Set HTML here which you want to see under this meta box.
    // Refer https://stackoverflow.com/questions/17651766/jquery-date-picker-multi-select-and-unselect
    // for multiselect datebox.
   echo '<input type="date" id="datePick" name=save-dates/>';
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );

Save Meta Value

function myplugin_save_postdata($post_id){
    if ( 'event' == $_POST['post_type'] ) {
        update_post_meta($post_id, 'save-dates', sanitize_text_field( $_REQUEST['save-dates'] ));
    }
}
add_action( 'save_post', 'myplugin_save_postdata' );

Get Meta Value

Now, wherever you want to show these dates. Just retrieve them from database and start using them. get_post_meta($post_id, 'save-dates',true);

Don't forget to explode(',', get_post_meta($post_id, 'save-dates',true)) before using them. As dates are being saved in comma format.

like image 178
Abhineet Verma Avatar answered Dec 14 '25 08:12

Abhineet Verma