在WordPress中,可以通过REST API获取自定义帖子类型的分类列表。以下是实现该功能的步骤:
add_action('rest_api_init', function () {
register_rest_route('custom/v1', '/categories', array(
'methods' => 'GET',
'callback' => 'get_custom_post_categories',
));
});
/custom/v1/categories
,请求方法为GET,回调函数为get_custom_post_categories
。get_custom_post_categories
:function get_custom_post_categories($request) {
$categories = get_terms(array(
'taxonomy' => 'your_custom_taxonomy', // 替换为你的自定义分类法名称
'hide_empty' => false,
));
$response = array();
foreach ($categories as $category) {
$response[] = array(
'id' => $category->term_id,
'name' => $category->name,
'slug' => $category->slug,
);
}
return rest_ensure_response($response);
}
get_terms
函数获取自定义分类法的分类列表。将your_custom_taxonomy
替换为你的自定义分类法的名称。现在,你可以通过访问https://your-wordpress-site.com/wp-json/custom/v1/categories
来获取自定义帖子类型的分类列表。返回的JSON数据将包含每个分类的ID、名称和别名。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云对象存储(COS)。
领取专属 10元无门槛券
手把手带您无忧上云