通过getEntityRecords调用在WordPress gutenberg中获取自定义字段



我正在尝试扩展getEntityRecords一点

我在区块中使用了元数据的自定义税

我已将数据添加到 API 调用中

wp-json/wp/v2/locations?per_page=100&orderby=name&order=asc&_fields=id%2Cname%2Cparent%2Clocation&_locale=user

返回

[
{
"id": 3,
"name": "Marriott's Cypress Harbour",
"parent": 0,
"location": "ORLANDO, FLORIDA"
},
{
"id": 2,
"name": "ss",
"parent": 0,
"location": ""
}
]

但是当我用getEntityRecords调用它时 select( 'core' (.getEntityRecords( 'taxonomy', 'locations', { per_page: -1} (

我得到

[{id: 3, name: "Marriott's Cypress Harbour", parent: 0}, {id: 2, name: "ss", parent: 0}]

我尝试在查询中添加字段

select( 'core' ).getEntityRecords( 'taxonomy', 'locations', { per_page: -1, fields: ['id', 'name', 'location'] } )

如何将我需要的额外数据(位置(获取到块上的对象中?

非常感谢

您必须在函数.php(或您的插件(中注册自定义字段,然后才能在 REST API 中使用:

function add_custom_field() {
register_rest_field( 'POST_TYPE',
'FIELD_NAME',
array(
'get_callback'  => 'rest_get_post_field',
'update_callback'   => null,
'schema'            => null,
)
);
}
add_action( 'rest_api_init', 'add_custom_field' );
function rest_get_post_field( $post, $field_name, $request ) {
return get_post_meta( $post[ 'id' ], $field_name, true );
}

在此示例中,将"POST_TYPE"更改为"位置",并将"FIELD_NAME"更改为"位置"。之后,您的位置字段应该可以直接在从getEntityRecords((返回的数据中访问

最新更新