要将请求Ajaxify化,需要两个部分,一个连接到wp\\u admin\\u ajax(如果希望wp\\u admin\\u ajax\\u nopriv可供未登录用户使用)的php函数和一个请求ajax的JavaScript。
PHP
add_action(\'wp_ajax_getpost_by_year\',\'process_getpost_by_year\');
add_action(\'wp_ajax_nopriv_getpost_by_year\',\'process_getpost_by_year\');
function process_getpost_by_year(){
$year = $_REQUEST[\'year\'];
$args = array(
\'post_type\' => \'post\',
\'ignore_sticky_posts\' => 1,
\'year\' => $year,
);
$the_query = new WP_Query( $args );
wp_send_json($the_query );
JavaScript
$.ajax({
url: \'your-wordpress-site.com/admin-ajax.php\',
data: {
year: year
action: \'getpost_by_year\'
},
})
.done(function(the_query) {
// do stuff with the query result here
console.log(the_query);
});
别忘了更新
your-wordpress-site.com
到您的网站url,
year
变量,以及