问题在于你如何访问帖子
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响应中。