2016-01-24 32 views
3

是否有可能返回基於其架構由WordPress的REST API v2的職位名單:WP API過濾器郵寄架構

對於模式的列表: http://v2.wp-api.org/reference/posts/

我想要篩選粘性領域,但其餘的領域也一樣。

到目前爲止,我有:

/wp-json/wp/v2/posts?filter[sticky]=true 
/wp-json/wp/v2/posts?filter[sticky]=1 

兩種方法都返回爲標準終點同樣的反應:

/wp-json/wp/v2/posts 

我已閱讀其他材料,詳細介紹瞭如何通過meta或定製taxonomies但我排序不要相信這是一樣的。

+0

它會出現[這還沒有實現](https://github.com/WP-API/WP-API/issues/924) –

+0

顯然它應該通過'filter [ignore_sticky_posts] = true | false',但這在* Beta11 *中不適用於我。正在進行的調查:https://github.com/WP-API/WP-API/issues/2210 –

回答

1

在閱讀WP-API Github回購文檔並查看和發佈問題後,很明顯filter[ignore_sticky_posts]應該切換預期的排序行爲,以便粘性帖子總是首先(默認)或忽略(由使用filter[ignore_sticky_posts]=true)。

但是,有currently a bug in WP API,使filter[ignore_sticky_posts]標誌不可用。

現在修復它的最好方法是到create you own custom endpoint以獲取數據庫中所有粘性帖子的數據或ID。通過查看代碼discussed in this threadthe WP-API documentation,我想加入以下代碼到你functions.php應該做的伎倆:

// Sticky posts in REST - https://github.com/WP-API/WP-API/issues/2210 
function get_sticky_posts() { 
    $posts = get_posts(
     array(
      'post__in' => get_option('sticky_posts') 
     ) 
    ); 

    if (empty($posts)) { 
     return null; 
    } 

    return $posts; 
} 
add_action('rest_api_init', function() { 
    register_rest_route('THEME_NAME/v1', '/sticky', array(
     'methods' => 'GET', 
     'callback' => 'get_sticky_posts', 
    )); 
}); 

如果GET/WP-JSON/THEME_NAME/V1 /粘,你應該得到所有粘性帖子的數組。

我希望這會有所幫助。

0

除了Laust Deleuran的回答(謝謝Laust!)之外,我創建了他的腳本的改變版本,允許您使用REST-apiembedded功能。

雖然這可能不是'最乾淨'的解決方案,但確實可以讓您充分利用wp-json的功能。


function get_sticky_posts(WP_REST_Request $request) { 

    $request['filter'] = [ 
     'post__in' => get_option('sticky_posts') 
    ]; 

    $response = new WP_REST_Posts_Controller('post'); 
    $posts = $response->get_items($request); 

    return $posts; 
} 

add_action('rest_api_init', function() { 
    register_rest_route('THEME_NAME/v1', '/sticky', array(
     'methods' => 'GET', 
     'callback' => 'get_sticky_posts', 
    )); 
}); 

這將輸出在同一個schemaposts作爲一個正常的/wp-json/wp/v2/posts查詢會迴應。