这就是我最终得到的,效果很好。
功能。php部件
<?php
function scripts_enqueue() {
if(is_page(\'archives\')) {
wp_enqueue_script(\'ajax_dropdown\', get_stylesheet_directory_uri() . \'/js/loadposts.js\',array(\'jquery\'));
wp_localize_script( \'ajax_dropdown\', \'myajax\', array(\'custom_nonce\' => wp_create_nonce(\'nonce-ajax-dropdown\'), \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
}
add_action( \'wp_enqueue_scripts\', \'scripts_enqueue\' );
function wp_ajax_load_posts(){
if(!wp_verify_nonce( $_GET[\'_wpnonce\'], \'nonce-ajax-dropdown\'))
die( \'Go away!\' );
$args = array(
\'year\' => trim($_GET[\'year\']),
\'monthnum\' => trim($_GET[\'month\']),
\'posts_per_page\' => -1,
\'orderby\' => \'date\',
\'cat\' => trim($_GET[\'cat\'] != "-1") ? trim($_GET[\'cat\']) : 0,
);
$ajaxsort = new WP_Query($args);
?>
<table id="archives-table">
<?php if ($ajaxsort->have_posts()) : while ($ajaxsort->have_posts()) : $ajaxsort->the_post();?>
<tr>
<td><a href=\'<?php the_permalink(); ?>\'><?php the_title(); ?></a></td>
<td><?php the_time(\'m/j/Y\'); ?></td>
<td><?php comments_popup_link(\'0 Comments\', \'1 Comment\', \'% Comments\'); ?></td>
<td><?php the_category();?>
</tr>
<?php
endwhile; else:
echo "<tr><td style=\'text-align: center; font-size: 15px; padding: 5px;\'>Nothing found.</td></tr>";
endif;
?>
</table>
<?php
exit;
}
add_action(\'wp_ajax_load_posts\', \'wp_ajax_load_posts\');
add_action(\'wp_ajax_nopriv_load_posts\', \'wp_ajax_load_posts\');
jquery部件
jQuery(document).ready(function($) {
$("#archive-browser select").change(function() {
$(".message").hide();
$("#archive-content").empty().html("<div style=\'text-align: center; padding: 30px;\'><img src=\'http://i.imgur.com/TA3o5.gif\' /></div>");
var date = $(\'#month-choice option:selected\').val();
var dateArray = $("#month-choice").val().split("/");
var year = dateArray[3];
var month = dateArray[4];
var cat = $(\'#cat\').val();
$.ajax({
url: myajax.ajaxurl,
type: \'GET\',
data: {
action: \'load_posts\',
_wpnonce: myajax.custom_nonce,
cat: cat,
month: month,
year: year,
},
success: function(data) {
if (date == \'no-choice\' && cat == "-1") {
$("#archive-content").empty().html(\'<table class="message" id="archives-table"><tr><td style="text-align: center; font-size: 15px; padding: 5px;">Please choose from above.</td></tr></table>\');
} else {
$("#archive-content").empty().html(data);
}
}
});
return false;
});
});