[英]Getting Wordpress REST-API content data inside a plugin with embed data
I'm creating my own routes for the wodpress api.我正在为 wodpress api 创建自己的路由。 At some point I need the rest content of the post and pages, to do this i have this function:
在某些时候,我需要帖子和页面的其余内容,为此我有这个功能:
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
but if I want to have the post content with embed data I change:但是,如果我想让帖子内容包含嵌入数据,我会更改:
new WP_REST_Request('GET', '/wp/v2/'.$type.'/' . $id);
to到
new WP_REST_Request('GET', '/wp/v2/'.$type.'/' . $id . '?_embed=true');
but this new request returns rest_no_route error但是这个新请求返回了rest_no_route错误
I have read the source code and now understand.我已经阅读了源代码,现在明白了。 The second parameter of new WP_REST_Request() is the route only without query parameters.
new WP_REST_Request() 的第二个参数是只有没有查询参数的路由。 The query parameters are specified in another method.
查询参数在另一种方法中指定。 Eg,
例如,
$request = new WP_REST_Request( 'GET', 'wp/v2/posts/999' );
$request->set_query_params( [ '_embed' => '1' ] );
However, this will not work as '_embed' is a special query parameter.但是,这不起作用,因为 '_embed' 是一个特殊的查询参数。 It is not handled by WP_REST_Server::dispatch(), which means rest_do_request() will not handle '_embed' as rest_do_request() is just a wrapper of WP_REST_Server::dispatch().
它不是由 WP_REST_Server::dispatch() 处理的,这意味着 rest_do_request() 不会处理“_embed”,因为 rest_do_request() 只是 WP_REST_Server::dispatch() 的包装器。
The reason '_embed' works from a URL is that URLs are processed by WP_REST_Server::serve_request() which calls WP_REST_Server::dispatch() but also calls WP_REST_Server::response_to_data() which calls WP_REST_Server::embed_links(). '_embed' 从 URL 工作的原因是 URL 由调用 WP_REST_Server::dispatch() 的 WP_REST_Server::serve_request() 处理,但也调用调用 WP_REST_Server::embed_links() 的 WP_REST_Server::response_to_data()。
If you want '_embed' to work in your get_rest_content() you will need to add the code for WP_REST_Server::embed_links().如果您希望“_embed”在您的 get_rest_content() 中工作,您将需要添加 WP_REST_Server::embed_links() 的代码。
I found a Github issue but the workaround is not working for me (at least for my code+WordPress version): https://github.com/WP-API/WP-API/issues/2857我发现了一个 Github 问题,但该解决方法对我不起作用(至少对于我的代码 + WordPress 版本): https : //github.com/WP-API/WP-API/issues/2857
Did you try adding the embeddable links to the response?您是否尝试将可嵌入链接添加到响应中?
//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.