繁体   English   中英

使用WordPress REST API获取多个帖子元

[英]Get multiple post meta with WordPress REST API

function my_rest_prepare_post( $data, $post, $request ) {
   $_data = $data->data;
   $_data[$field] = get_post_meta( $post->ID, 'my_custom_field_key', true );
   $data->data = $_data;
   return $data;
}
add_filter( 'rest_prepare_post', 'my_rest_prepare_post', 10, 3 );

上面是我用来在API中包含元值的代码。 但是我想包含多个元,我试图在my_custom_field_key添加my_custom_field_key分隔的不同元键,但是我只显示了第一个键的值。

第二个问题是它仅显示元值,如何在JSON响应中包含key:value?

//returns an array of metadata get_metadata('post', $post->ID)

https://codex.wordpress.org/Function_Reference/get_metadata

在类似的问题中修改我接受的答案,我已经在本地站点中测试了工作功能。

add_action( 'rest_api_init', 'add_custom_fields' );
function add_custom_fields() {
register_rest_field(
'post', 
'custom_fields', //New Field Name in JSON RESPONSEs
array(
'get_callback'    => 'get_custom_fields', // custom function name 
'update_callback' => null,
'schema'          => null,
 )
);
}

然后定义您的函数以获取自定义字段

function get_custom_fields( $object, $field_name, $request ) {
return get_post_meta( $object['id'] );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM