簡體   English   中英

使用嵌入數據在插件中獲取 Wordpress REST-API 內容數據

[英]Getting Wordpress REST-API content data inside a plugin with embed data

我正在為 wodpress api 創建自己的路由。 在某些時候,我需要帖子和頁面的其余內容,為此我有這個功能:

function get_rest_content($id, $type)
{
    if ($id > 0) {
        $request = new WP_REST_Request('GET', '/wp/v2/'.$type.'/' . $id);
        $response = rest_do_request($request)->data;
    } else {
        $response = null;
    }


    if (empty($response)) {
        return new WP_Error('wpse-error',
            esc_html__('No '.$type. 'found', 'wpse'),
            ['status' => 404]);
    }
    return $response;
}

$post_1 = get_rest_content(1,'posts') // give me the rest content of the post with id=1

但是,如果我想讓帖子內容包含嵌入數據,我會更改:

new WP_REST_Request('GET', '/wp/v2/'.$type.'/' . $id);

new WP_REST_Request('GET', '/wp/v2/'.$type.'/' . $id . '?_embed=true');

但是這個新請求返回了rest_no_route錯誤

我已經閱讀了源代碼,現在明白了。 new WP_REST_Request() 的第二個參數是只有沒有查詢參數的路由。 查詢參數在另一種方法中指定。 例如,

$request = new WP_REST_Request( 'GET', 'wp/v2/posts/999' );
$request->set_query_params( [ '_embed' => '1' ] );

但是,這不起作用,因為 '_embed' 是一個特殊的查詢參數。 它不是由 WP_REST_Server::dispatch() 處理的,這意味着 rest_do_request() 不會處理“_embed”,因為 rest_do_request() 只是 WP_REST_Server::dispatch() 的包裝器。

'_embed' 從 URL 工作的原因是 URL 由調用 WP_REST_Server::dispatch() 的 WP_REST_Server::serve_request() 處理,但也調用調用 WP_REST_Server::embed_links() 的 WP_REST_Server::response_to_data()。

如果您希望“_embed”在您的 get_rest_content() 中工作,您將需要添加 WP_REST_Server::embed_links() 的代碼。

我發現了一個 Github 問題,但該解決方法對我不起作用(至少對於我的代碼 + WordPress 版本): https : //github.com/WP-API/WP-API/issues/2857

您是否嘗試將可嵌入鏈接添加到響應中?

//get the post
$response = rest_do_request($request)->get_data();

//add the embeddable links 
$results_with_embed = rest_ensure_response(rest_get_server()->response_to_data( $response, true ));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM