我有一个默认查询,当未设置ajax过滤器时加载默认状态。
它应该设置为 6 个帖子,但它加载了我所有的帖子,这是我的默认状态。
默认状态应该是在Ajax请求发生之前。
默认帖子
<?php
$string = basename($wp->request); ;
$string = str_replace('-', '_', $string);
$new_string = $string;
$query_args = array(
'posts_per_page' => 6,
'post_status' => 'publish',
'post_type' => $string
);
$the_query = new WP_Query($query_args);
if ($the_query->have_posts()) :
while ($the_query->have_posts()) : $the_query->the_post();
get_template_part('template-parts/posts-filter/single-post');
endwhile;
wp_reset_postdata();
endif;
?>
阿贾克斯
<?php // the ajax function
add_action('wp_ajax_filterPosts', 'filterPosts');
add_action('wp_ajax_nopriv_filterPosts', 'filterPosts');
function filterPosts()
{
$response = [
'posts' => "",
];
$all_args = array(
'posts_per_page' => -1, // returns all posts
'post_status' => 'publish',
);
$filter_args = array(
'post_status' => 'publish',
);
if ($_POST['limit']) {
$filter_args['posts_per_page'] = $_POST['limit'];
}
if (isset($_POST['offset'])) {
$filter_args['offset'] = max (0, (int)$_POST['offset']);
}
if ($_POST['post_type_js']) {
$filter_args['post_type'] = $_POST['post_type_js'];
}
if ($_POST['category']) {
$filter_args['cat'] = $_POST['category'];
// Get the total number of posts for the category
$all_args['cat'] = $_POST['category'];
}
$filter_query = new WP_Query($filter_args);
$all_query = new WP_Query($all_args);
if ($filter_query->have_posts()) :
while ($filter_query->have_posts()) : $filter_query->the_post();
$response['posts'] .= load_template_part('/template-parts/posts-filter/single-post');
endwhile;
wp_reset_postdata();
endif;
echo json_encode($response);
die();
}
如果没有发送ajax请求,我预计只会加载6个帖子,
Post_per_page
在这里似乎不起作用,有什么原因吗?
我们缺少很多上下文,例如: