【发布时间】:2020-09-01 13:46:21
【问题描述】:
我正在使用 Wordpress Rest API 将内容从 Wordpress 网站导入 PHP 应用程序。 这并不复杂,只是一个包含帖子列表和各个帖子页面的主页。
我在 API 响应中添加了一些字段,特别是用于获取帖子中插入的第一张图片的 url。
这是这部分的代码:
add_action('rest_api_init', function () {
register_rest_field('post', 'post_images', array(
'get_callback' => 'get_first_image',
'update_callback' => null,
'schema' => null
));
});
function get_first_image($obj, $name, $request)
{
$images = get_attached_media('image', $obj['id']);
$imagesArray = (array) $images;
reset($imagesArray);
$firstImageId = current($imagesArray)->ID;
$imageSrc = wp_get_attachment_image_url($firstImageId);
return $imageSrc;
}
当我在主页中列出帖子时它工作正常,但在单个帖子页面中该字段为空。我能想出的唯一解释是我为单个帖子提供了这个自定义端点:
function post_by_slug(WP_REST_Request $request)
{
$postSlug = $request->get_param('post_slug');
$lang = $request->get_param('my_lang');
$myPost = get_page_by_path($postSlug, OBJECT, 'post');
$targetPostId = apply_filters('wpml_object_id', $myPost->ID, 'post',
false, $lang);
$targetPost = get_post($targetPostId);
$postController = new \WP_REST_Posts_Controller($targetPost->post_type);
$response = $postController->prepare_item_for_response($targetPost,
$request);
return rest_ensure_response($response);
}
add_action('rest_api_init', function () {
register_rest_route('pc/v1',
"/post-slug/(?P<post_slug>\S+)/(?P<my_lang>\w+)", [
'methods' => 'GET',
'callback' => 'post_by_slug',
'args' => [
'post_slug' => 'required',
'my_lang' => 'required'
]
]);
});
在我的应用中,我这样称呼它:
$client = new Client([
'base_uri' => 'http://example.com/wp-json/pc/v1/',
'headers' => [
'Content-Type' => 'application/json',
"Accept" => "application/json",
],
'verify' => false,
]);
var_dump(json_decode($client->get("post-slug/$slug/$lang")
->getBody()->getContents()));
奇怪的是,直接从浏览器访问同一个端点我可以正确看到所有字段。我错过了什么?
【问题讨论】:
标签: wordpress guzzle wordpress-rest-api wpml