Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.