wp rest api get posts with their meta

I am a total wp newb and I am struggling to get posts with all their meta(wp_postmeta table) via the WP REST API.
http://v2.wp-api.org/reference/posts/

Any guidance is greatly appreciated. Thanks!

Related posts

Leave a Reply

3 comments

  1. if you want single field use:

    register_rest_field( 'post', 'views', array(
    'get_callback' => function ( $data ) {
        return get_post_meta( $data['id'], 'hs_views', true );
    }, ));
    

    don’t forget change hs_views field to what you want

    if you want all fields use:

    register_rest_field( 'post', 'meta', array(
    'get_callback' => function ( $data ) {
        return get_post_meta( $data['id'], '', '' );
    }, ));
    

    check reference: get_post_meta

  2. Whilst register_rest_route is good for extensive customization, WordPress allows you to expose custom meta fields in the default WordPress REST API, without having to build your own endpoints.

    You can use register_meta to expose certain WordPress Meta fields for certain post types. By default, meta fields aren’t registered to be exposed to the Rest API.

    register_meta('post', 'type', [
            'type' => 'string',
            'single' => true,
            'show_in_rest' => true,
        ]);
    

    In this example, we set default ‘posts’ to show the meta field with the key “type” in the rest api. Specifically, show_in_rest set to true achieves this.

    Read More -> https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/#using-register_rest_field-vs-register_meta