WordPress REST AOI get & add posts with meta data

 

http://dd.meiji2.com/wp-json/wp/v2/posts/53238

6down voteaccepted

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

 

 

I implemented it, Here is the code:

Checkout the WordPressPCL source code , and add this field to Post.cs :

pubic class Post{
    public Dictionary<string, object> Metadata { get; set; }
}

add this code to your current theme functions.php or create an plugin:

add_action( 'rest_api_init', function(){
register_rest_field('post', 'metadata', array(
    'get_callback' => function ($post) {
            $id = $post->ID ? $post->ID : ($post->id ? $post->id : $post['id']);
            $r = get_post_meta($id, '', '');
            return $r ? $r : $id;
    },
    'update_callback' => function ($data, $post, $field_name) {
            $id = $post->ID ? $post->ID : ($post->id ? $post->id : $post['id']);
            if ($id) {
                foreach ($data as $key => $value) {
                    if (!add_post_meta($id, $key, $value)) {
                          update_post_meta($id, $key, $value);
                     }
                }
            }
            return true;
    },
));

register_rest_field(
    'post',
    'content_raw',
        array(
            'get_callback' => function ($post, $field_name, $request) {
            $id = $post->ID ? $post->ID : ($post->id ? $post->id : $post['id']);
            $post = get_post($id);
            return $post->post_content;
        }
    )
);
});

use:

var metadata = new Dictionary<string, object>() {
    { "customfield1", "111" },
    { "customfield2", "222" },
};
var post = new Post{
    //...
    Metadata=metadata,
}
//client.Posts.Create(post);

发表评论

电子邮件地址不会被公开。