我想在REST API中显示自定义post类型的post meta。我正在通过slug查询帖子
https://www.example.com/wp-json/wp/v2/event?slug=custom-post-slug
add_filter( 'register_post_type_args', 'my_post_type_args', 10, 2 );
function my_post_type_args( $args, $post_type ) {
if ( 'event' === $post_type ) {
$args['show_in_rest'] = true;
// Optionally customize the rest_base or rest_controller_class
$args['rest_base'] = 'event';
$args['post__meta'] = get_post_meta( $post->ID, true );
$args['rest_controller_class'] = 'WP_REST_Posts_Controller';
}
return $args;
}
发布于 2020-05-13 00:29:25
在使用register_post_type
函数注册自定义post类型时,应将其添加到REST API中。在参数列表中,可以找到show_in_rest
、rest_base
和rest_controller_base
(register_post_type doc)。
然后,您可以使用register_rest_field
函数(documentation)向接口添加元字段。
这里有一个你需要做的例子:
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
function create_api_posts_meta_field() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'post', 'post-meta-fields', array(
'get_callback' => 'get_post_meta_for_api',
'schema' => null,
)
);
}
function get_post_meta_for_api( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id );
}
只需将“post”替换为您的自定义post类型即可。
希望它能帮上忙!
https://stackoverflow.com/questions/61755748
复制相似问题