我假设您希望在post\\u类型JSON的每个项目中都包含这些分类法数据,但分类法端点和JSON响应的逻辑是相同的。
我认为有两种方法可以实现这一目标。
使用过滤数据rest_prepare_post_type
过滤器(Reference) 或
使用register_rest_field
作用(Reference)我推荐第二种方法。这是我最近使用的自定义帖子类型案例1:rest\\u prepare\\u post\\u type在第一种情况下,您将使用rest_prepare_post_type
筛选以获取数据,生成所需的数据,将其添加到数据数组并返回筛选后的数据。在这种情况下,如果立柱类型为“立柱”,则挂钩为rest\\U prepare\\U post。
/**
* @summary Filters post rest response
*
* @description Filters post rest response removing or adding certain information
* @param object $data The response object.
* @param object $post The original post type object.
* @param object $request Request used to generate the response.
* @return object $data The filtered response object.
*/
function wpse_283452_rest_prepare_post($data, $post, $request) {
$_data = $data->data;
// say you want to remove author from the response
unset($_data[\'author\']);
// if you want to ADD fields, you would do the logic here and...
// add it to the $_data array
$data->data = $_data;
// and finally return it
return $data;
}
add_filter(\'rest_prepare_post\', \'wpse_283452_rest_prepare_post\', 10, 3);
如果要对分类法使用相同的方法,可以使用rest_prepare_taxonomy/
(reference)案例2:register\\u rest\\u字段(推荐)
您将使用register_rest_field
函数并使用回调按所需方式填充它/**
* Registers a new field on an existing WordPress object type.
*
* @since 4.7.0
*
* @global array $wp_rest_additional_fields Holds registered fields, organized
* by object type.
*
* @param string|array $object_type Object(s) the field is being registered
* to, "post"|"term"|"comment" etc.
* @param string $attribute The attribute name.
* @param array $args {
* Optional. An array of arguments used to handle the registered field.
*
* @type string|array|null $get_callback Optional. The callback function used to retrieve the field
* value. Default is \'null\', the field will not be returned in
* the response.
* @type string|array|null $update_callback Optional. The callback function used to set and update the
* field value. Default is \'null\', the value cannot be set or
* updated.
* @type string|array|null $schema Optional. The callback function used to create the schema for
* this field. Default is \'null\', no schema entry will be returned.
* }
*/
register_rest_field(
\'post\',
\'wpse_283452_taxonomies\',
array(
\'get_callback\' => function ($object, $field_name, $request) {
return wpse_283452_taxonomies_callback($object);
},
)
);
/**
* @summary Return and array with taxonomy info
*
* @description Returns an array with taxonomy information in a custom way
* @param object $object The rest item original object
* @return array $custom_taxonom an array with taxonomy terms with their information in a custom way
*/
function wpse_283452_taxonomies_callback($object) {
$post_id = $object[\'id\'];
$terms = wp_get_post_terms(
$post_id,
\'business_type\',
array(
\'fields\' => \'all\',
)
);
// here you should construct an array with the information in $terms in the way/structure you want
return $terms;
}
对于分类法,可以使用分类法slug而不是“post”作为register\\u rest\\u字段的第一个参数。就是这样。
如果有效,请告诉我。