WordPress Ajax获取指定分类/子分类总文章数返回0问题
自定义文章类型分类文章数量返回0的修复方案
目标
让total变量准确等于所选分类/子分类下的custom_post类型文章总数。
当前问题
尝试获取分类下的文章数量时,返回值始终为0。
问题根源
代码存在几个核心错误:
- PHP端没有实际统计分类文章数,反而把前端传过来的0赋值给了统计参数
- 统计查询缺少自定义文章类型和分类ID的条件,查的是默认文章类型而非
custom_post - 前端冗余传递
total值,且getTotal方法未携带分类ID,后端无法定位要统计的分类 - 响应未返回
total字段,前端拿不到正确数据
修复后的PHP代码
<?php // Ajax处理函数 add_action('wp_ajax_filterPosts', 'filterPosts'); add_action('wp_ajax_nopriv_filterPosts', 'filterPosts'); function filterPosts() { $response = [ 'posts' => "", 'total' => 0, // 初始化total字段 ]; // 用于统计总数的查询参数 $total_args = [ 'posts_per_page' => -1, 'post_status' => 'publish', 'post_type' => !empty($_POST['post_type_js']) ? $_POST['post_type_js'] : 'post', ]; $filter_args = [ 'post_status' => 'publish', ]; if ($_POST['limit']) { $filter_args['posts_per_page'] = max(0, (int)$_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']; // 给统计总数的参数添加分类条件 $total_args['cat'] = $_POST['category']; } // 查询要显示的文章 $filter_query = new WP_Query($filter_args); // 查询分类下的总文章数 $total_query = new WP_Query($total_args); $response['total'] = $total_query->found_posts; // 获取准确总数 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(); }
修复后的JavaScript代码
Alpine.data("filterPosts", (adminURL) => ({ posts: "", limit: 6, total: null, category: null, post_type_js: post_id, // 确保这里是自定义文章类型的slug,比如'custom_post' showDefault: true, showFiltered: false, offset: 0, loading: false, loadingMore: false, filterPosts(id) { this.showDefault = false; this.showFiltered = true; this.category = id; this.offset = 0; this.fetchPosts(); }, loadMore() { this.loadingMore = true; this.offset += 6; this.fetchPosts(true); }, fetchPosts(append = false) { this.loading = true; const formData = new FormData(); formData.append("action", "filterPosts"); formData.append("limit", this.limit); formData.append("post_type_js", this.post_type_js); formData.append("offset", this.offset); if (this.category) { formData.append("category", this.category); } fetch(adminURL, { method: "POST", body: formData, }) .then(res => res.json()) .then(res => { this.posts = append ? this.posts + res.posts : res.posts; this.total = res.total; // 更新total值 this.loading = false; this.loadingMore = false; }); }, init() { // 如果需要默认加载某个分类,可在此设置this.category = 默认分类ID this.fetchPosts(); }, }));
核心修复说明
- PHP端:
- 新增专门的统计查询参数
total_args,包含自定义文章类型和分类条件 - 使用
found_posts获取总数,比直接计数查询结果更高效 - 确保响应返回
total字段
- 新增专门的统计查询参数
- JS端:
- 移除冗余的
getTotal方法,直接在fetchPosts中获取并更新总数 - 修复文章拼接逻辑(原
concat适用于数组,这里是字符串直接相加) - 去掉前端传递
total的无用逻辑,总数完全由后端计算返回 - 完善加载状态的重置逻辑
- 移除冗余的
内容的提问来源于stack exchange,提问作者Beep
相关产品推荐
相关产品推荐

