我是第一次使用带有响应前端的wordpress rest api。我可以获取文本并将其渲染得很好。但是,当我发出GET请求时,将获得该对象作为精选媒体:
"_embedded": {
"wp:featuredmedia": [
{
"code": "rest_post_invalid_id",
"message": "Invalid post ID.",
"data": {
"status": 404
}
}
]
}
如何正确检索特色图片,这样我不会收到此消息?
这是我的GET请求:
let dataURL = "http://localhost:81/wp-json/wp/v2/movies?_embed";
fetch(dataURL)
.then(res => res.json())
.then(res => {
this.setState({
movies: res
});
});
预先感谢您的帮助
答案 0 :(得分:0)
希望以下代码将帮助您获取各种尺寸的精选图像。请将代码粘贴到functions.php中。
//ADD FEATURED IMAGE WITH ALL SIZE
add_action( 'rest_api_init', 'tris_endpoints_featured_images' );
function tris_endpoints_featured_images() {
register_rest_field( get_post_types() ,
'featured_images',
array(
'get_callback' => 'tris_endpoints_featured_images_cb',
'update_callback' => null,
'schema' => null,
)
);
}
function tris_endpoints_featured_images_cb( $object, $field_name, $request ) {
if(has_post_thumbnail($object[ 'id' ])){
$image_sizes = get_intermediate_image_sizes();
foreach ($image_sizes as $key => $size) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $object[ 'id' ]), $size );
$all_images[$size]= $image[0];
}
return $all_images;
}else{
return null;
}
}