代码之家  ›  专栏  ›  技术社区  ›  Stamp

自定义字段未显示在WordPress REST API响应中

  •  1
  • Stamp  · 技术社区  · 11 月前

    我正在尝试为我在WordPress中的自定义文章类型添加一个自定义字段到REST API响应。该字段应该显示my_custom_field的值。但是,自定义字段未出现在响应中。

    这是我使用的代码:

    function add_custom_fields_to_rest_api() {
        register_rest_field(
            'my_custom_post_type',
            'my_custom_field',
            array(
                'get_callback' => 'get_custom_field_value',
                'update_callback' => null,
                'schema' => null,
            )
        );
    }
    
    function get_custom_field_value($object, $field_name, $request) {
        return get_post_meta($object->ID, $field_name, true);
    }
    
    add_action('rest_api_init', 'add_custom_fields_to_rest_api');
    

    我做错了什么?

    1 回复  |  直到 11 月前
        1
  •  0
  •   haduki    11 月前

    问题在于你如何访问帖子 ID get_custom_field_value 功能。这个 $object 参数应被视为数组,而不是对象。

    以下是你的代码应该是什么样子的:

    function add_custom_fields_to_rest_api() {
        register_rest_field(
            'my_custom_post_type',
            'my_custom_field',
            array(
                'get_callback' => 'get_custom_field_value',
                'update_callback' => null,
                'schema' => null,
            )
        );
    }
    
    function get_custom_field_value($object, $field_name, $request) {
        return get_post_meta($object['id'], $field_name, true);
    }
    
    add_action('rest_api_init', 'add_custom_fields_to_rest_api');
    

    在the get_custom_field_value 功能, $object['id'] 正确访问帖子 身份证件 这应当确保 my_custom_field 按预期显示在REST API响应中。