0

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

1 Answer 1

1

You 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)

5
  • That looks awesome :) Let me give it a quick try out at my end before I accept else I think we're on to a winner
    – Tom J Nowell
    Commented Nov 9, 2018 at 14:53
  • So, how was it? All good? :)
    – Sally CJ
    Commented Nov 12, 2018 at 0:36
  • I haven't had a chance to test yet
    – Tom J Nowell
    Commented Nov 12, 2018 at 0:45
  • Success! It worked!
    – Tom J Nowell
    Commented Nov 12, 2018 at 0:53
  • Awesome! (sorry if I bothered your weekend.. heh)
    – Sally CJ
    Commented Nov 12, 2018 at 1:06

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.