具有自定义 post 类型的 Wordpress API V2 自定义字段

Wordpress API V2 custom fields with custom post types

我正在尝试将我的自定义帖子添加到 Wordpress API,它也有自定义字段。

我可以通过 /wp-json/wp/v2/fruit 在 API 上查看自定义帖子类型。

但是自定义字段没有显示,如何将它们添加到 API?

看看“Extending the REST API / Modifying Responses", and in particular at register_rest_field

查看 this example:

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