Search code examples
wordpresswordpress-rest-apiwp-api

Add Post Meta Fields via WP API v2


I'm trying to play with the WP API v2 and insert posts from Postman.

If I post this raw request, it creates a post just fine:

{
  "title": "Test Title",
  "content": "Test Content",
}

However, I'm trying to add some custom field values to this as well, and I can't seem to get them to work. This request creates a post, but doesn't add any meta fields:

{
  "title": "Test Title",
  "content": "Test Content",
  "meta": {
    "foo": "bar",
    "foo2": "bar2"
  }
}

How do I POST the meta fields foo and foo2 with the values bar and bar2 through the API endpoint https://my-site.com/wp-json/wp/v2/posts?

Edit: It also appears custom fields don't get pulled natively in GET requests. I put this code in a mu-plugin:

add_filter( 'rest_prepare_post', 'xhynk_api_post_meta', 10, 3 );
function xhynk_api_post_meta( $data, $post, $context ){
    $meta = get_post_custom( $post->ID );

    if( $meta ) {
        $data->data['meta'] = $meta;
    }

    return $data;
}

Which at least lets me view it on a GET request. However I still can't seem to get it to POST via Postman. Even adding "status": "publish" will cause the new post to publish instead of being a draft like it is by default. Are there any hooks or filters I can use on API POST requests to make sure the custom fields are added?


Solution

  • to handle metas on insertion and update, you can do it with action rest_insert_ + post type

    add_action("rest_insert_page", function (\WP_Post $post, $request, $creating) {
    
    
        $metas = $request->get_param("meta");
    
        if (is_array($metas)) {
    
            foreach ($metas as $name => $value) {
                update_post_meta($post->ID, $name, $value);
            }
    
        }
    
    
    }, 10, 3);