2017-03-02 66 views
1

如何获得prev和next post wordpress api中的帖子,我无法得到这个,如何让json prev和next在wordpress中不需要API 我想要获得slu posts文章我可以在单篇文章中使用next prev,如何让蛞蝓,链接,或ID后明年和prevWordpress API json,如何在单个帖子中获得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 ?> 

这样,但JSON使用https://codex.wordpress.org/Function_Reference/previous_post_link

+0

任何运气?我在这里坐在同一条船上。 – tonkihonks13

回答

0

我99%肯定的WordPress的API不提供此,作为在“休息”环境中没有多大意义。

许多Wordpresses旧功能旨在使生活更轻松(如previous_post_link),并可以通过以下方式进行工作:a)做出假设(您正在按照顺序列出的帖子构建博客)和b)制作自己的规范。

通过引入Rest(并且能够声称它是Rest-ish),除非特别定义为关系,否则引用前一个/下一个元素没什么意义。例如,“平面”休息端点有意义地将乘客作为关系聆听:/api/planes/f0556/passengers但是,由于上下文可能改变(下一班要离开的班机是否到达?),因此下一次/上一班班机没有任何意义。 )。

取而代之,您需要查询/api/planes/(index)端点以获取该端口上的所有航班,并挑选出您需要的。

2

晚会有点晚 - 但这里是答案。

虽然我同意@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" 
    }, 
    ... 
    } 
] 
相关问题