# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rest-api, navigation, headless
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/rest-adjacent-posts-field/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Previous and Next Post Links in the REST API" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
