wp rest api get posts with their meta wp rest api get posts with their meta wordpress wordpress

wp rest api get posts with their meta


I found an easy solution for this. In the current theme - functions.php add the following code:

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

It will return posts / post with all it's meta. I.e.http://localhost/rest_api/wp-json/wp/v2/postsorhttp://localhost/rest_api/wp-json/wp/v2/post/58

post meta will be in "metadata"


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