简体   繁体   中英

Wordpress API json, how to get prev and next posts in single post?

how to get prev and next posts in single post wordpress api, i can't get this, how to make json prev and next like in wordpress without API i want to get slug posts i can use next prev in single post, how to get slug, link, or id post for next and prev

<?php
$prev_post = get_previous_post();
if (!empty( $prev_post )): ?>
  <a href="<?php echo $prev_post->guid ?>"><?php echo $prev_post->post_title ?></a>
<?php endif ?>

like this but use in json https://codex.wordpress.org/Function_Reference/previous_post_link

A little late to the party – but here is an answer.

While I agree with @Chris answer that a REST API is different from the PHP API available for themes, sometimes we still build the same frontends from the data, right?

If I want to show links on my blog to the next and previous post, I don't want to send 3 requests to the API.

As a solution I included this in my plugin containing the API adjustments for the specific project:

// Add filter to respond with next and previous post in post response.
add_filter( 'rest_prepare_post', function( $response, $post, $request ) {
  // Only do this for single post requests.
  if( $request->get_param('per_page') === 1 ) {
        global $post;
        // Get the so-called next post.
        $next = get_adjacent_post( false, '', false );
        // Get the so-called previous post.
        $previous = get_adjacent_post( false, '', true );
        // Format them a bit and only send id and slug (or null, if there is no next/previous post).
        $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;
}, 10, 3 );

Which gives you something like this:

[
  {
    "ID": 123,
    ...
    "next": {
      "id": 212,
      "slug": "ea-quia-fuga-sit-blanditiis"
    },
    "previous": {
      "id": 171,
      "slug": "blanditiis-sed-id-assumenda"
    },
    ...
  }
]

I'm 99% positive the Wordpress API doesn't offer this, as it makes little sense in a "Rest" environment.

A lot of Wordpresses older functions are aimed to make life easier (like previous_post_link) and can kind of work by a) making assumptions (you are building a blog with posts listed in order) and b) making up their own spec.

By introducing Rest (and to be able to claim it is Rest-ish) it wouldn't make much sense to reference the previous / next element unless it was specifically defined as a relationship. For example, it makes sense for a "plane" rest endpoint to listen passengers as a relationship: /api/planes/f0556/passengers but it would not make sense to have next/previous flight because the context could change (is it the next flight to depart? to arrive?).

Instead, you would need to query the /api/planes/ (index) endpoint to get all flights on either side of this one, and pick out what you need.

I was facing the same problem. I was not able to modify the wordpress functions.php so i had to built a solution with the REST API.

The key was to get the root post id and get the post which was published right after/before this root post.

Here is my solution:

public function getAdjacentPost(Post $post, string $direction = WordPressApi::ADJACENT_RIGHT): ?Post
{
    //$dateEdge = $post->getCreatedAt()->format(\DateTimeInterface::ISO8601);
    $dateEdge = $post->getCreatedAt()->format('Y-m-d H:i:s');
    $query = [
        'exclude'  => $post->id,
        'per_page' => 1,
        'orderby'  => 'date',
    ];
    switch ($direction) {
        case WordPressApi::ADJACENT_RIGHT:
            $query['order'] = 'asc';
            $query['after'] = $dateEdge;
            break;
        case WordPressApi::ADJACENT_LEFT:
            $query['order'] = 'desc';
            $query['before'] = $dateEdge;
            break;
        default:
            throw new \InvalidArgumentException(sprintf('Invalid direction: %s!', $direction));
    }

    $posts = $this->client->requestArray('posts', $query);
    return count($posts) === 0
        ? null
        : new Post($posts[0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM