2

What filters will transform a normal WP_Post object (as returned from get_posts()) to match the post objects returned from native REST API endpoints?

I have a custom endpoint which returns a WP_Post object, but rest_ensure_response just returns a simple JSON dump of the post:

function endpoint() {
    $p = get_posts(['include' => 10]);
    return rest_ensure_response($p);
}
//  wp-json/custom/v1/example
[{ "ID": 10, "post_date": "2017-01-23 16:15:13", "post_content": "<p>..." }] 

Returning the same post natively from the REST API remaps the data to something like this (keys are lowercase, dates are normalized, content is rendered):

// wp-json/wp/v2/posts/10
[{ "id": 10, "date": "2017-01-23T16:15:13", "content": {"rendered": "<p>..."}}]

How can I make the posts from my custom endpoint match those from native endpoints? Clearly the functions/filters exist, manually recreating them would be silly.

1 Answer 1

3

The prepare_item_for_response method of the WP_REST_Posts_Controller class "Prepares a single post output for response" by translating every property of the post object for output from the REST API. The method doesn't run statically, so we need to instantiate a controller in our endpoint.

Here's a simple example endpoint:

function endpoint( $request ) {
    $p = get_post( $request['id'] );
    $postController = new \WP_REST_Posts_Controller($p->post_type);
    $response = $postController->prepare_item_for_response( $p, $request );
    return rest_ensure_response( $response );
}

The resulting JSON response is identical to what is returned from the native endpoint.

Note that prepare_item_for_response only deals with singular WP_Post objects, a collection of posts will need to have this applied to each item.

It may also be possible to use WP_REST_Posts_Controller->get_item method. That wants to pull the post id from a request, but looks like it could be faked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.