Previous and Next Post Links in the REST API
Adds a navigation field to single posts in the REST API with the ID, title and link of the previous and next posts, so apps can build "read next" buttons.
Opens WPIDE on
Code
add_action( 'rest_api_init', function () {
register_rest_field( 'post', 'navigation', array(
'get_callback' => function ( $object, $field, $request ) {
// Skip collection requests: adjacent-post lookups are one query each.
if ( ! $request->get_param( 'id' ) ) {
return null;
}
$current = get_post( $object['id'] );
if ( ! $current ) {
return null;
}
$GLOBALS['post'] = $current;
$format = function ( $post ) {
return $post ? array( 'id' => $post->ID, 'title' => get_the_title( $post ), 'link' => get_permalink( $post ) ) : null;
};
$result = array(
'previous' => $format( get_previous_post() ),
'next' => $format( get_next_post() ),
);
wp_reset_postdata();
return $result;
},
'schema' => array( 'type' => array( 'object', 'null' ), 'context' => array( 'view' ), 'readonly' => true ),
) );
} );
Notes
The field is only computed for single-post requests, so post lists stay fast.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.