I have a custom post type with a parent post, and code to fetch this post in Javascript via a GET
request, all is working very well. The API endpoints I'm using are those provided by core when show_in_rest
is set to true on registration.
However, I want a little more information about the parent post than its ID, and I don't want to make a second request to fetch it, so how might I extend the response from the REST API to include that information? Or any other arbitrary information for that matter.
In particular it would be great to include the title and URL, but a full post object would be good too. Note that I do not want to create a custom endpoint from scratch, but extend the existing core endpoint
I have a custom post type with a parent post, and code to fetch this post in Javascript via a GET
request, all is working very well. The API endpoints I'm using are those provided by core when show_in_rest
is set to true on registration.
However, I want a little more information about the parent post than its ID, and I don't want to make a second request to fetch it, so how might I extend the response from the REST API to include that information? Or any other arbitrary information for that matter.
In particular it would be great to include the title and URL, but a full post object would be good too. Note that I do not want to create a custom endpoint from scratch, but extend the existing core endpoint
Share Improve this question asked Nov 9, 2018 at 1:18 Tom J Nowell♦Tom J Nowell 61.2k7 gold badges79 silver badges150 bronze badges1 Answer
Reset to default 1You can modify the response data via the rest_prepare_{$this->post_type}
filter, like so for a custom post type test_cpt
(registered with hierarchical
and show_in_rest
set to true
):
add_filter( 'rest_prepare_test_cpt', 'rest_prepare_test_cpt' );
function rest_prepare_test_cpt( WP_REST_Response $response ) {
$data = $response->get_data();
if ( ! empty( $data['parent'] ) ) {
if ( ! $parent_post = get_post( $data['parent'] ) ) {
return $response;
}
// Include only some post data.
$data['parent_data'] = [
'title' => get_the_title( $parent_post ), // or just $parent_post->post_title
'excerpt' => get_the_excerpt( $parent_post ), // or just $parent_post->post_excerpt
'link' => get_permalink( $parent_post ),
];
// Or include the whole data..
// $data['parent_data'] = $parent_post; // object
// $data['parent_data'] = $parent_post->to_array(); // array
$response->set_data( $data );
}
return $response;
}
WP_REST_Response
extends WP_HTTP_Response
which defines the get_data()
and set_data()
methods.
Note that the code may not work if you set a different rest_controller_class
when you register the post type. (The default controller class is WP_REST_Posts_Controller
which fires the filter used above)