How to add a filter to a custom post type to get adjacent custom posts via the REST API

by Carsten H   Last Updated June 14, 2019 13:08 PM

I need to get the adjecent posts of a custom post type "projects". The custom post type works in general and I get the a projects list and single projects via GET request. In addition want to add the adjecent projects for simple navigation on the single project page in the response.

I am using

'rest_base'     => 'projects'

The below code works for standard posts and I am trying to figure out how to adapt it so I can access the custom post in the same way. How do I access the custom post type correctly? Any help appreciated.

function chrest_adjacent_posts( $response, $post, $request ) {
    global $post;
    $next = get_adjacent_post( false, '', false );
    $previous = get_adjacent_post( false, '', true );
    $response->data['next'] = ( is_a( $next, 'WP_Post') ) ? array( "id" => $next->ID, "slug" => $next->post_name ) : null;
    $response->data['previous'] = ( is_a( $previous, 'WP_Post') ) ? array( "id" => $previous->ID, "slug" => $previous->post_name ) : null;
    return $response;

add_filter( 'rest_prepare_post', 'chrest_adjacent_posts', 10, 3 );

Related Questions

API Rest Custom Post Type doesn't return all data

Updated February 24, 2017 17:08 PM

Get the Category Name instead of ID from WP-API

Updated December 06, 2017 19:08 PM

Custom Post Type and API REST is not working

Updated July 25, 2018 21:08 PM