Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 394
Sorin Ciocoiu Avatar asked Jun 05 '16 12:06

Sorin Ciocoiu


1 Answers

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/posts or http://localhost/rest_api/wp-json/wp/v2/post/58

post meta will be in "metadata"

like image 189
Sorin Ciocoiu Avatar answered Sep 22 '22 13:09

Sorin Ciocoiu