在 WP REST API 中获取 post 元数据

Get post meta in WP REST API

我想在我的 REST API 中显示自定义 post 类型的 post 元数据。我正在通过 slug

查询 post
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;
    }

在使用 register_post_type 函数注册时,您应该将自定义 post 类型添加到 REST API 中。在参数列表中,您会找到 show_in_restrest_baserest_controller_base (register_post_type doc).

然后,您可以使用 register_rest_field 函数 (documentation) 将元字段添加到 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 );
}

只需将 'post' 替换为您自定义的 post 类型即可。

希望对您有所帮助!