Bài viết sẽ hướng dẫn các bạn tạo ra một lịch biểu ghi chú những sự kiện đã, đang và sẽ diễn ra trong năm của bạn.
Xem qua demo khi bạn thực hiện song tut này nhé
Bước 1: Tạo file Plugin
Bạn tạo một folder trong thư mục wp-content/plugins có tên gọi verbose-event-calendar để chứa plugin của chúng ta. Tiếp theo tạo 1 file index.php có nội dung bên dưới
1 2 3 4 5 6 7 8 9 10 | <?php /* Plugin Name: Verbose Event Calendar Version: 1.0 Description: Custom post type for creating events and display visually in a calendar control. Author URI: http://www.innovativephp.com Author: Rakhitha Nimesh License: GPL2 */ ?> |
Bước 2: Tìm hiểu cấu trúc thư mục của một plugin
- Images – Bao gồm tất cả file ảnh sử dụng cho Plugin
- javascripts – Bao gồm các đoạn mã javascript cho Plugin
- stylesheets – Bao gồm các file css cho Jquery Verbose Calendar
- themes – Css cho Jquery Date Picker
- ui – Javascript file cho Jquery Date Picker
- verboseCalAdmin.js – Custom javascript sử dụng cho admin
- verboseCalCustom.js – Custom javascript sử dụng cho user
- styles.css – Css cho Plugin
- index.php – Code PHP chứa plugin
- README.md – readme của Verbose
Bước 3: Enqueue JavaScript and CSS Files
Đoạn mã sau cho phép hiển thị verbose calendar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php function verbose_calendar_scripts() { global $post; wp_enqueue_script('jquery'); wp_register_style('verboseCalCustomStyles', plugins_url('styles.css', __FILE__)); wp_enqueue_style('verboseCalCustomStyles'); wp_register_script('verboseCal', plugins_url('javascripts/jquery.calendar/jquery.calendar.min.js', __FILE__)); wp_enqueue_script('verboseCal'); wp_register_style('verboseCalMainStyles', plugins_url('stylesheets/main.css', __FILE__)); wp_enqueue_style('verboseCalMainStyles'); wp_register_style('verboseCalStyles', plugins_url('javascripts/jquery.calendar/calendar.css', __FILE__)); wp_enqueue_style('verboseCalStyles'); wp_register_script('verboseCalCustom', plugins_url('verboseCalCustom.js', __FILE__)); wp_enqueue_script('verboseCalCustom'); $config_array = array( 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('reward-nonce') ); wp_localize_script('verboseCal', 'calendarData', $config_array); } add_action('wp_enqueue_scripts', 'verbose_calendar_scripts'); ?> |
Đoạn mã sau cho giao diện admin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php function verbose_calendar_admin_scripts() { global $post; wp_enqueue_script('jquery'); wp_register_style('verboseCalCustomStyles', plugins_url('styles.css', __FILE__)); wp_enqueue_style('verboseCalCustomStyles'); wp_register_style('jqueryUIALL', plugins_url('themes/base/jquery.ui.all.css', __FILE__)); wp_enqueue_style('jqueryUIALL'); wp_register_script('jqueryUICore', plugins_url('ui/jquery.ui.core.js', __FILE__)); wp_enqueue_script('jqueryUICore'); wp_register_script('jqueryUIWidget', plugins_url('ui/jquery.ui.widget.js', __FILE__)); wp_enqueue_script('jqueryUIWidget'); wp_register_script('jqueryUIDate', plugins_url('ui/jquery.ui.datepicker.js', __FILE__)); wp_enqueue_script('jqueryUIDate'); wp_register_script('verboseCalAdmin', plugins_url('verboseCalAdmin.js', __FILE__)); wp_enqueue_script('verboseCalAdmin'); } add_action('admin_enqueue_scripts', 'verbose_calendar_admin_scripts'); ?> |
Bước 4: Đăng ký Event như một Custom Post của wordpress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php function register_custom_event_type() { $labels = array( 'name' => _x('Events', 'event'), 'singular_name' => _x('Event', 'event'), 'add_new' => _x('Add New', 'event'), 'add_new_item' => _x('Add New Event', 'event'), 'edit_item' => _x('Edit Event', 'event'), 'new_item' => _x('New Event', 'event'), 'view_item' => _x('View Event', 'event'), 'search_items' => _x('Search Events', 'event'), 'not_found' => _x('No events found', 'event'), 'not_found_in_trash' => _x('No events found in Trash', 'event'), 'parent_item_colon' => _x('Parent Event:', 'event'), 'menu_name' => _x('Events', 'event'), ); $args = array( 'labels' => $labels, 'hierarchical' => false, 'supports' => array('title', 'editor'), 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'has_archive' => true, 'query_var' => true, 'can_export' => true, 'rewrite' => true, 'capability_type' => 'post' ); register_post_type('event', $args); } add_action('init', 'register_custom_event_type'); ?> |
Bước 6: Tạo các trường thuộc tính
Add Event Info Meta Box
1 2 3 4 5 6 | <?php add_action('add_meta_boxes', 'add_events_fields_box'); function add_events_fields_box() { add_meta_box('events_fields_box_id', 'Event Info', 'display_event_info_box', 'event'); } ?> |
Add Event Field
1 2 3 4 5 6 7 8 9 10 11 12 | <?php function display_event_info_box() { global $post; $values = get_post_custom($post->ID); $eve_start_date = isset($values['_eve_sta_date']) ? esc_attr($values['_eve_sta_date'][0]) : ''; $eve_end_date = isset($values['_eve_end_date']) ? esc_attr($values['_eve_end_date'][0]) : ''; wp_nonce_field('event_frm_nonce', 'event_frm_nonce'); $html = "<label>Event Start Date</label><input id='datepickerStart' type='text' name='datepickerStart' value='$eve_start_date' /> <label>Event End Date</label><input id='datepickerEnd' type='text' name='datepickerEnd' value='$eve_end_date' />"; echo $html; } ?> |
Add Date Picker for Event Field
1 2 3 4 5 6 7 | <script> $jq =jQuery.noConflict(); $jq(document).ready(function() { $jq("#datepickerStart").datepicker(); $jq("#datepickerEnd").datepicker(); }); </script> |
Bước 7: Kiểm tra sự kiện tạo Event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <script> $jq('#post').submit(function() { $jq('.ver_cal_err').remove(); if($jq("#post_type").val() =='event') { var err = 0; if($jq("#title").val() == '') { $jq("#title").after("<div class='ver_cal_err'>Event Title cannot be empty</div>"); err++; } if($jq("#datepickerStart").val() == '' || $jq("#datepickerEnd").val() == '') { $jq("#datepickerEnd").after("<div class='ver_cal_err'>Start Date and End Date is required</div>"); err++; } var start = $jq('#datepickerStart').datepicker('getDate'); var end = $jq('#datepickerEnd').datepicker('getDate'); var days = (end - start)/1000/60/60/24; if(days<0) { $jq("#datepickerEnd").after("<div class='ver_cal_err'>End Date should be greater than Start Date.</div>"); err++; } if(err>0) { return false; } else { return true; } } }); </script> |
Bước 8: Lưu Event vào Database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php add_action('save_post', 'save_event_information'); function save_event_information($post_id) { // Bail if we're doing an auto save if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; // if our nonce isn't there, or we can't verify it, bail if (!isset($_POST['event_frm_nonce']) || !wp_verify_nonce($_POST['event_frm_nonce'], 'event_frm_nonce')) return; // if our current user can't edit this post, bail if (!current_user_can('edit_post')) return; if (isset($_POST['datepickerStart'])) update_post_meta($post_id, '_eve_sta_date', esc_attr($_POST['datepickerStart'])); if (isset($_POST['datepickerEnd'])) update_post_meta($post_id, '_eve_end_date', esc_attr($_POST['datepickerEnd'])); } ?> |
Bước 9: Tạo shortcode
Shortcode của chúng ta sẽ có dạng [ verbose_calendar/ ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php function verbose_calendar() { global $post; return "<div id='main-container'></div><div id='popup_events'> <div class='pop_cls'></div> <div id='popup_events_list'> <div id='popup_events_head'></div> <div id='popup_events_bar'></div> <div id='event_row_panel' class='event_row_panel'></div> <div id='popup_events_bottom'></div> </div> </div>"; } add_shortcode("verbose_calendar", "verbose_calendar"); ?> |
Đoạn shortcode bên trên sẽ insert các tag HTML cần có cho calendar. Chúng ta có thể sử dụng jquery bên dưới để gọi nó ra. Đoạn code có trong file verboseCalCustom.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <script> $jq =jQuery.noConflict(); $jq(document).ready(function() { $jq("#main-container").calendar({ tipsy_gravity: 's', // How do you want to anchor the tipsy notification? (n / s / e / w) post_dates : ["1","2"], click_callback: calendar_callback, // Callback to return the clicked date year: "2012", // Optional, defaults to current year - pass in a year - Integer or String scroll_to_date: false // Scroll to the current date? }); $jq(".pop_cls").on("click",function() { $jq("#popup_events").fadeOut("slow"); }); }); </script> |
Sau khi làm xong, chúng ta sẽ có được thành quả như này
Bước 10: Đăng ký event với calendar
Công việc tiếp theo của tut này là bạn sẽ phải làm công việc là load các event có trong cơ sở dữ liệu để hiển thị ra calendar. Verbose Calendar sử dụng hàm g.prototype.print để thực hiện hiển thị ra calendar. Và thế chúng ta có thể tùy chỉnh nó trong file jquery.calendar.min.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <script> g.prototype.print=function(c) { postDetailsArr = []; var verboseElement = this.element; $jq.post(calendarData.ajaxUrl, { action:"get_posts_for_year", nonce:calendarData.nonce, currentYear:e.options.year }, function(result, textStatus) { $jq.each(result, function(index, data) { if(data.type == 'event') { if(postDetailsArr[data.startDate]) { postDetailsArr[data.startDate].push(data); } else { postDetailsArr[data.startDate] = []; postDetailsArr[data.startDate].push(data); } postArr.push(data.startDate); } else { if(postDetailsArr[data.post_date]) { postDetailsArr[data.post_date].push(data); } else { postDetailsArr[data.post_date] = []; postDetailsArr[data.post_date].push(data); } postArr.push(data.post_date); } }); }, "json"); }; </script> |
Và bây giờ chúng ta sẽ thực hiện truy vấn từ cơ sở dữ liệu và bind kết quả ra cho AJAX
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <?php add_action('wp_ajax_nopriv_get_posts_for_year', 'get_posts_for_year'); add_action('wp_ajax_get_posts_for_year', 'get_posts_for_year'); function get_posts_for_year() { global $post, $wpdb; $allEvents = array(); $sql = "SELECT $wpdb->posts.guid,$wpdb->posts.post_title,DATE_FORMAT(post_date, '%m-%d-%Y') as post_date FROM $wpdb->posts WHERE Year($wpdb->posts.post_date)='" . $_POST['currentYear'] . "' and post_status='publish' and post_type='post' "; $allPosts = array(); $yearlyPosts = $wpdb->get_results($sql, ARRAY_A); foreach ($yearlyPosts as $key => $singlePost) { $singlePost['type'] = 'post'; array_push($allEvents, $singlePost); } $sql = "SELECT $wpdb->posts.ID,$wpdb->posts.guid,$wpdb->posts.post_title,DATE_FORMAT(post_date, '%m-%d-%Y') as post_date FROM $wpdb->posts inner join $wpdb->postmeta on $wpdb->posts.ID=$wpdb->postmeta.post_id WHERE $wpdb->postmeta.meta_key='_eve_sta_date' and Year(STR_TO_DATE($wpdb->postmeta.meta_value, '%m/%d/%Y'))='" . $_POST['currentYear'] . "' and post_status='publish' and post_type='event'"; $yearlyEvents = $wpdb->get_results($sql, ARRAY_A); foreach ($yearlyEvents as $key => $singleEvent) { $startDate = str_replace("/", "-", get_post_meta($singleEvent['ID'], '_eve_sta_date')); $endDate = str_replace("/", "-", get_post_meta($singleEvent['ID'], '_eve_end_date')); $singleEvent['startDate'] = $startDate[0]; $singleEvent['endDate'] = $endDate[0]; $singleEvent['type'] = 'event'; array_push($allEvents, $singleEvent); } echo json_encode($allEvents); exit; } ?> |
Bước 11: Hiển thị Event
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script> var calendar_callback = function(date) { $jq("#event_row_panel").html(""); date.month = (date.month < 10) ? "0"+date.month : date.month; date.day = (date.day < 10) ? "0"+date.day : date.day; var activeDate = date.month+"-"+date.day+"-"+date.year; $jq("#popup_events_head").html("Events for "+activeDate); var dailyEvents = postDetailsArr[activeDate]; var eventHTML = ""; $jq.each(dailyEvents, function(index, data) { if(data.type=='event') { eventHTML += "<div class='event_row'><div class='event_title'><a href='"+data.guid+"' >"+data.post_title+"</a></div><div class='event_dates'>Start Date : <span>"+data.startDate+"</span> End Date : <span>"+data.endDate+"</div></div>"; } else { eventHTML += "<div class='post_row'><div class='post_title'><a href='"+data.guid+"' >"+data.post_title+"</a></div><div class='post_dates'>Published Date : <span>"+data.post_date+"</span></div></div>"; } }); $jq("#event_row_panel").html(eventHTML); $jq("#popup_events").fadeIn("slow"); } </script> |
OK vậy là xong. Một tutorials hoàn chỉnh giúp bạn có thể tạo ra calendar của riêng mình. Bạn có thể tạo ra nhiều trường hơn nữa cho plugin để phục vụ cho mục đích của bạn. Chúc bạn thành công
http://wp.tutsplus.com
[jbutton link=”http://www.innovativephp.com/wordpress-demos/my-guest-post-calendar/” color=”orange”]Demo[/jbutton][jbutton link=”https://www.kleii.com/f/50607c4c47700ad155000070″ color=”orange” icon=”download”]Download code[/jbutton]
You must log in to post a comment.