为了账号安全,请及时绑定邮箱和手机立即绑定

在 WP REST API 中获取帖子元

在 WP REST API 中获取帖子元

Go
慕村9548890 2023-03-11 15:19:51
我想在我的 REST API 中显示自定义帖子类型的帖子元。我正在通过 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;    }
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

在使用该函数注册时,您应该将自定义帖子类型添加到 REST API register_post_type。在参数列表中,您会找到show_in_rest,rest_base和rest_controller_base( register_post_type doc )。


然后,您可以使用register_rest_field函数(文档)向 API 添加元字段。


有一个你需要做什么的例子:


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 );

}

只需将“帖子”替换为您的自定义帖子类型即可。


查看完整回答
反对 回复 2023-03-11
  • 1 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信