我正在使用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()));
奇怪的是,从浏览器直接访问同一个端点 我可以正确地看到所有的字段。我是不是漏掉了什么明显的东西?
只是回答我自己的问题,因为我已经找到了是什么原因导致端点从我的浏览器正常工作,但通过Guzzle访问时不工作。
问题是我是以管理员的身份登录的,所以我使用的WPML插件来管理网站上的多种语言,设置了这个cookie。
wp-wpml_current_admin_language_d41d8cd98f00b204e9800998ecf8427e:"de"
所以这个问题与这个插件有关,我实际上是在使用这个插件 post_by_slug
function.不知为何,像我这样指定语言是不够的,或者只是起到不同的作用,不确定。
$targetPostId = apply_filters('wpml_object_id', $myPost->ID, 'post', false, $lang);
我可以找到两种解决方案
1)使用插件明确设置语言。switch_lang()
方法。
function post_by_slug(WP_REST_Request $request) {
global $sitepress;
$postSlug = $request->get_param('post_slug');
$lang = $request->get_param('my_lang');
$sitepress->switch_lang($lang);
2)改变guzzle的GET请求,将语言作为查询参数传递,这似乎可以自动与插件一起工作。
$response = $client->get("post-slug/$slug", ['query' => ['lang' => $lang]])->getBody()->getContents();
我意识到这是一个非常特殊的问题,但也许会对其他人有所帮助。