Working on one project, I got an idea to create a custom posts calendar which will be updated by ajax call.
First, I forked get_calendar() function. I copied the function to functions.php file and renamed to get_calendar_local().
I changed the view of the calendar and made it look as following:
Left/right buttons are coded as following:
$calendar_output = '
Then I added proper handling for left/right buttons in javascript:
jQuery(function($) { $("a.calendar").live("click", function() { month = $(this).attr("data-month"); nonce = $(this).attr("data-nonce"); $(".calendar-data").fadeOut(); $.ajax({ type : "post", dataType : "json", url : myAjax.ajaxurl, data : {action: "calendar_action", month : month, nonce: nonce, pll_load_front: true}, success: function(response) { if(response.type == "success") { $("#calendar-content").html(response.content) $(".calendar-data").fadeIn(); } }, error: function(){ $(".calendar-data").fadeIn(); } }) return false; }); });
I use Polylang for multilingual support and I needed to specify language in order to localize ajax request.
The following lines should be added to functions.php actions ‘wp_enqueue_scripts’.
wp_localize_script( 'local', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php?lang='.pll_current_language("slug") ))); wp_enqueue_script( 'local' );
The most interesting part – adding ajax function support to functions.php:
add_action("wp_ajax_calendar_action", "calendar_action", 6); function calendar_action() { global $monthnum, $year, $wp_locale; if ( !wp_verify_nonce( $_REQUEST['nonce'], "calendar_nonce")) { exit("No naughty business please"); } list($year, $monthnum) = explode("-", $_REQUEST['month']); $result["type"]="success"; $result["content"] = get_calendar_local(false, false); if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { echo json_encode($result); } else { header("Location: ".$_SERVER["HTTP_REFERER"]); } die(); }