![](/img/trans.png)
[英]Plugin WordPress JSON API - How get posts for category with offset?
[英]Wordpress API json, how to get prev and next posts in single post?
如何在单个帖子 wordpress api 中获取上一个和下一个帖子,我无法得到这个,如何在没有 API 的 wordpress 中制作 json 上一个和下一个帖子 我想获得 slug 帖子我可以在单个帖子中使用下一个上一个帖子,如何获得下一个和上一个的 slug、链接或 ID 帖子
<?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 ?>
像这样,但在 json https://codex.wordpress.org/Function_Reference/previous_post_link
派对有点晚了 - 但这是一个答案。
虽然我同意@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"
},
...
}
]
我99%肯定Wordpress API没有提供这个,因为它在“休息”环境中毫无意义。
许多Wordpresses较旧的功能旨在使生活更轻松(如previous_post_link),并且可以通过a)做出假设(您正在构建一个按顺序列出的帖子的博客)和b)制定自己的规范。
通过引入Rest(并且能够声称它是Rest-ish),引用前一个/下一个元素没有多大意义,除非它被特别定义为关系。 例如,对于“飞机”休息终点来说,将乘客视为一种关系是有意义的: /api/planes/f0556/passengers
但由于上下文可能会改变(下一次/之前的飞行)是没有意义的飞机离开?到达?)。
相反,您需要查询/api/planes/
(index)端点以获取此端点的任何一侧的所有航班,并选择您需要的航班。
我面临着同样的问题。 我无法修改 wordpress functions.php,所以我不得不使用 REST API 构建一个解决方案。
关键是获取根帖子 id 并获取在此根帖子之后/之前发布的帖子。
这是我的解决方案:
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.