晚会有点晚 - 但这里是答案。
虽然我同意@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"
},
...
}
]
任何运气?我在这里坐在同一条船上。 – tonkihonks13