[英]Get post meta in WP REST API
I want to show post meta for custom post type in my REST API.我想在我的 REST API 中显示自定义帖子类型的帖子元。 I am querying post via slug
我正在通过 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;
}
You should add your custom post type to the REST API when registering it with the register_post_type
function.使用
register_post_type
function 注册时,您应该将自定义帖子类型添加到 REST API。 In the list of arguments, you'll find show_in_rest
, rest_base
and rest_controller_base
( register_post_type doc ).在 arguments 列表中,您会找到
show_in_rest
、 rest_base
和rest_controller_base
( register_post_type doc )。
Then, you can use the register_rest_field
function (documentation) to add meta fields to the API.然后,您可以使用
register_rest_field
function (文档)将元字段添加到 API。
There's an example for what you need to do:有一个你需要做的例子:
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 );
}
Simply replace 'post' with your custom post type.只需将“帖子”替换为您的自定义帖子类型即可。
Hope it helps!希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.