The AJAX request would query for the dates it requires to display. With Lazy fetching set, if you switch from month to week or day views it won’t bother making another request, since it doesn’t need to. This is outlined in the fullcalendar documentation.
As for using this method, see this question on how to obtain the admin-ajax.php url properly.
Next, you need to set the fullcalendar source appropriately and then define the ajax action. The following is taken from my Event Organiser
plugin. So feel free to nose around to get the details (you’ll want frontend.js
in the js folder and event-organiser-ajax.php
in the includes folder).
The Event source
jQuery(".eo-fullcalendar").fullCalendar({
lazyFetching: 'true',
events: function(start, end, callback) {
jQuery.ajax({
url: MYAJAX.url+"?action=mycalendaraction",
dataType: 'JSON',
data: {
start: jQuery.fullCalendar.formatDate(start, 'yyyy-MM-dd'),
end:jQuery.fullCalendar.formatDate(end, 'yyyy-MM-dd')
},
success: function(data) {
callback(data);
}
})
}
});
By default the start and end dates are as timestamps, but my query required it in YYYY-MM-DD format. The MYAJAX.url
is the admin-ajax.php url which you set, as explained in the linked question, by using wp_localize_script
.
Finally, you need to add the appropriate actions to deal with the request:
if ( isset( $_REQUEST['action'] ) AND 'mycalendaraction' === $_REQUEST['action'] ) {
//For logged in users.
do_action( "wp_ajax_{$_REQUEST['action']}" );
// For non-logged in users:
do_action( "wp_ajax_nopriv_{$_REQUEST['action']}" );
}
add_action( 'wp_ajax_mycalendaraction', 'get_my_events' );
add_action( 'wp_ajax_nopriv_mycalendaraction', 'get_my_events' );
function get_my_events() {
//$_GET['start'] the start date
//$_GET['end'] the end date
//perform query
//Let $events_array be the array of events with each event being an appropriate array (for instance with 'title','start','end','allDay' keys - see fullcalendar documentation).
//Echo result and exit
echo json_encode($event_sarray);
exit;
}
In the above I am assuming the calendar is for both logged-in and non-logged-in users (hence both actions). You way also want to perform some nonce checks (see the linked question). Note the action is the same as that set in the ajax url of the ‘Event source’ section.
What should be included in each event array is given in the fullcalendar documentation under ‘Event Object’. On the javascript side an associative array (i.e. an event) is recieved as an object with values given by the values in the array: I.e. event['key']
becomes event.key
Disclaimer: The above code has been changed to make things clearer and so has not been tested.