聚会有点晚了——但这里有一个答案。
虽然我同意 @Chris 的回答,即 REST API 与可用于主题的 PHP API 不同,但有时我们仍会根据数据构建相同的前端,对吧?
如果我想在我的博客上显示下一篇和上一篇文章的链接,我不想向 API 发送 3 个请求。
作为解决方案,我将其包含在我的插件中,其中包含针对特定项目的 API 调整:
// 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 );
这会给你这样的东西:
[
{
"ID": 123,
...
"next": {
"id": 212,
"slug": "ea-quia-fuga-sit-blanditiis"
},
"previous": {
"id": 171,
"slug": "blanditiis-sed-id-assumenda"
},
...
}
]