我有与您相同的用例—从React调用WP-API—并遇到了相同的问题。
不幸的是,WP-API不支持按父类别过滤。为了支持它,您可以扩展API的功能,添加一个新的过滤器,该过滤器将运行tax_query
幕后,类似于Faye\'s answer.
假设您有权访问Wordpress应用程序,请修改functions.php
在当前主题中添加:
// Add parent_category filter to REST API
function rest_filter_by_parent_category($args, $request)
{
if (isset($request[\'parent_category\'])) {
$parent_category = sanitize_text_field($request[\'parent_category\']);
$args[\'tax_query\'] = [
[
\'taxonomy\' => \'category\',
\'field\' => \'term_id\',
\'include_children\' => true,
\'operator\' => \'IN\',
\'terms\' => $parent_category,
]
];
}
return $args;
}
add_filter(\'rest_post_query\', \'rest_filter_by_parent_category\', 10, 3);
然后,只需使用新过滤器查询API:
/posts?parent_category=28
Alternative
如果无法修改
functions.php
文件(例如,您正在查询外部博客),然后您可以:
获取所有类别(您可能已经在应用程序中完成)构建一个反向索引,形状为[parentId: number] => number[]
使用构建查询categories=C1,C2...
使用反向索引
const axios = require("axios");
// Query all the categories from Wordpress
const fetchCategories = async () => {
const params = [
"_fields[]=id",
"_fields[]=parent",
// Ideally you would use a better pagination strategy
"page=1",
"per_page=100",
];
// Using axios, but you could use native fetch or any other library
return axios
.get(`WORDPRESS_SITE/wp-json/wp/v2/categories?${params.join("&")}`)
.then((result) => result.data);
};
// Build reverse index
const buildParentIndex = (categories) => {
return categories.reduce((acc, category) => {
const hasParent = !!category.parent; // Root categories have ID 0
const parentId = hasParent ? category.parent : category.id;
if (!acc[parentId]) {
acc[parentId] = [];
}
if (hasParent) {
acc[parentId].push(category.id);
}
return acc;
}, {});
};
(async () => {
// You should pre-compute & cache these, as fetching the categories
// and building the index on every request will heavily affect
// the latency of your request
const categories = await fetchCategories();
const parentIndex = buildParentIndex(categories);
const fetchPostsByParentId = (categoryId) =>
axios
.get(
`WORDPRESS_SITE/wp-json/wp/v2/posts?categories${parentIndex[
categoryId
].join("&")}`
)
.then((result) => result.data);
})();
如果可能,我建议使用第一种方法-修改
functions.php
— 因为它更简单、更一致。JS替代方案可能需要缓存,以避免延迟受到影响,这会带来许多潜在问题(例如陈旧的缓存)。
Source