我正在尝试使用高级自定义字段在类别响应中添加类别图像字段类别图像。
但是该字段返回null,这是我的代码。
function addCategoryImage(){
register_rest_field('category', 'categoryImage', array(
'taxonomy' => 'category',
'get_callback' => function() {
$category = get_the_category();
return get_field('category_image', 'category_' . $category_id);
}
));
};
add_action('rest_api_init', 'addCategoryImage');
get_field('category_image','category_'。$ category_id);如果category_id为null,该函数将不返回任何内容,因此请尝试返回$ category并检查是否返回任何值,如果返回,则仍然需要获得term_id(如果帖子可以包含多个类别),则需要指定词条以获取ID。
一般建议:在处理API或内部函数时,请始终打印出您要使用的所有变量,以首先检查它们是否具有任何值。不要编写完整的代码并进行最终测试,因为如果存在问题,将很难找出原因。
在此处查看更多详细信息:https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/