2017-03-02 149 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" 
    }, 
    ... 
    } 
] 
相關問題