Add multiple dates to custom post type in Wordpress

梦想的初衷 提交于 2019-12-22 12:27:13

问题


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.



来源:https://stackoverflow.com/questions/24302980/add-multiple-dates-to-custom-post-type-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!