Match REST API post output from custom endpoint

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.

Leave a Comment