4

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?

Xhynk
  • 13,513
  • 8
  • 32
  • 69

1 Answers1

14

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);
mmm
  • 1,070
  • 1
  • 7
  • 15
  • You, my friend, are an absolute life saver! I've been pulling my hair out for 2 days on this! However, can I ask what the purpose of `\WP_Post $post` is in the function declaration? I attempted it with the following, and it worked: `add_action( 'rest_insert_post', function( $post, $request, $creating ){` just wondering what that piece was for in your answer? – Xhynk Oct 26 '17 at 22:40
  • it's a type declaration http://php.net/functions.arguments#functions.arguments.type-declaration – mmm Oct 27 '17 at 07:40
  • 1
    Thx it really helps a lot <3 – Axel Paris Jun 23 '21 at 10:02
  • Finally, Legend! – stepho Nov 19 '22 at 20:26