繁体   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