REST API prepare response data - markhowellsmead/helpers GitHub Wiki
When returning data from a custom WordPress REST API endpoint, we need
to ensure that the data is properly prepared using the prepare_item_for_response
method in the WP_REST_Posts_Controller
class. This ensures that any custom
meta fields (etc.) which are registered for the response are included
in the response automatically.
Code
private function prepareRestResponse(mixed $data, WP_REST_Request $request, bool $single = false, int $code = 200): WP_REST_Response|null
{
if (is_null($data)) {
return new WP_REST_Response(null, $code);
}
$return_single = false;
if ($single) {
$return_single = true;
$data = [$data];
}
$return = [];
$controller = new WP_REST_Posts_Controller($this->post_type);
foreach ($data as $entry) {
$entry_data = $controller->prepare_item_for_response($entry, $request);
$return[] = $controller->prepare_response_for_collection($entry_data);
}
if ($return_single) {
return new WP_REST_Response($return[0], $code);
}
return new WP_REST_Response($return, $code);
}
Usage
$companies = $this->entriesByUser($user->ID);
if (empty($companies)) {
return new WP_REST_Response([], 200);
}
return $this->prepareRestResponse(data: $companies, single: false, request: $request);