Add multiple dates to custom post type in Wordpres

2019-05-29 10:16发布

问题:

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!

回答1:

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.



回答2:

A Wordpress way might be to store the dates as a serialized array (google: php serialize), in the meta data for the custom post type. If you need to search the dates, it might be better to store each date as a naked peice of data (not a serialzed array) in the post meta data. One thing to remember, is that if this site needs l18n (multi language, locale support) dates can get tricky! Look up (Wordpress, l18n, dates). Consider storing dates as unix timestamps if you need to do any sorting.