您必须注意,ajax请求是一个全新的http请求,因此$query
变量在发送ajax请求的页面中定义,但not 在页面中设置接收请求的页面。
这意味着您已经完全重新创建了查询,而没有更改参数。
也就是说,你有2 可能性:
1: 如果查询是自定义查询(您可以使用WP_Query
) 您可以编写一个函数,返回该查询并从页面和ajax操作中的函数挂钩中调用它:
// in functions.php or in plugin
function my_custom_query( $posts_per_page = 10 ) {
$args = array(
\'posts_per_page\' => $posts_per_page,
// other args here
);
return new WP_Query( $args );
}
// then inside the page
$query = my_custom_query();
while ( $query->have_posts() ) { $query->the_post();
// your loop code here
}
// and handling ajax action
add_action(\'wp_ajax_the_function_here\', \'my_ajax_loop\');
add_action(\'wp_ajax_nopriv_the_function_here\', \'my_ajax_loop\');
function my_ajax_loop() {
$query = my_custom_query( -1 );
while ( $query->have_posts() ) { $query->the_post();
// your loop code here
}
die();
}
查询是主查询如果要复制主查询,请更改一个或多个参数,然后通过以下命令将查询变量传递给脚本
wp_localize_script
然后通过ajax将它们传递给处理ajax操作的函数,例如:
add_action(\'wp_enqueue_script\', \'add_my_scripts\');
function add_my_scripts() {
// here I\'m assuming the javascript file where you have the code you posted
// is called \'myscript.js\' and resides in \'js\' subfolder inside theme folder
wp_enqueue_script(\'my_script\', get_template_directory_uri() . \'/js/myscript.js\');
global $wp_query;
$qv = $wp_query->query;
wp_localize_script(\'my_script\', \'my_script_data\', array(\'query\' => $qv) );
}
之后,在js文件中,您可以:
jQuery.ajax({
type: \'POST\',
url: ajaxurl, // example.com/wp-admin/admin-ajax.php is defined in my js file
data: {
action: \'the_function_here\',
ajaxnonce: YTajax.ajaxnonce, // Also defined
query: my_script_data.query // Defined by \'wp_localize_script\'
},
success: function(data, textStatus, XMLHttpRequest) {
jQuery(\'#bodyForOutput\').html(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
现在,您可以像这样处理ajax请求:
// and handling ajax action
add_action(\'wp_ajax_the_function_here\', \'my_ajax_loop\');
add_action(\'wp_ajax_nopriv_the_function_here\', \'my_ajax_loop\');
function my_ajax_loop() {
$args = (array) filter_var(INPUT_POST, \'query\');
$args[\'posts_per_page\'] = -1;
$query = new WP_Query($args);
while ( $query->have_posts() ) { $query->the_post();
// your loop code here
}
die();
}