【问题标题】:Wordpress Category Image in Categories response using Advanced Custom Fields returning null使用高级自定义字段返回 null 的类别响应中的 Wordpress 类别图像
【发布时间】:2020-02-14 07:26:05
【问题描述】:

我正在尝试使用高级自定义字段在类别响应中添加类别图像字段类别图像。

但该字段返回 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');

【问题讨论】:

  • 请检查$category 是否返回任何内容并且此函数不在循环内,所以get_the_category 需要帖子ID 来返回特定帖子的类别? $category_id 是怎么来的?您的代码中似乎缺少我,请尝试$cateogry->term_id
  • $category 返回空数组。
  • 那么你必须先解决这个问题,然后你才能从类别中获取category_image

标签: wordpress advanced-custom-fields wordpress-rest-api


【解决方案1】:

get_field('category_image', 'category_' . $category_id);如果 category_id 为空,函数将不返回任何内容,因此请尝试返回 $category 并检查剂量是否返回任何内容,如果返回,您仍然需要获取 term_id 如果帖子可以包含多个类别,那么您需要指定术语 slug 以获取 id。

一般建议:在处理 API 或内部函数时,请务必首先打印出您使用的所有变量,以检查它们是否具有任何值。不要编写完整的代码并进行最终测试,因为出现问题很难找出原因。

在此处查看更多详细信息: https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

【讨论】:

    【解决方案2】:

    在做了一些研究之后,我找到了我正在寻找的确切答案。回调函数有这些参数。

        'get_callback' => function ( $object, $field_name, $request, $object_type ) {
        // ...
    }
    

    所以我得到了每个类别的 $object,我可以从中获取术语 id。这是更新后的代码。

    function addCategoryImage(){
        register_rest_field('category', 'categoryImage', array(
            'get_callback' => function($cat) {
                return get_field('category_image', 'category_' . $cat['id']);
            }
    
        ));
    };
    add_action('rest_api_init', 'addCategoryImage');
    

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2015-12-30
      • 2018-04-29
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多