您有两个可以使用的选项 - 您可以修改您当前的产品rest api URL 以便在一次调用中返回图片url,或者您可以修改您的functions.php通过在下面添加此代码:
修改functions.php
//Register new route - fetch product and its image together in one request
function product_route() {
register_rest_field(
'product',
'featured_image_url',
array(
'get_callback' => 'getImagesUrl',
'update_callback' => null,
'schema' => null,
)
);
}
add_action( 'rest_api_init', 'product_route' );
//get images with URL
function getImagesUrl( $object, $field_name, $request ) {
//get products image URL
$product_img_url = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), 'large' );
//return image url
return $product_img_url['0'];
}
将上述代码添加到functions.php后,您可以像这样在单个请求中使用fetch
fetch(state.source.api + "/wp/v2/product")
.then((response) => response.json())
.then((data) => {
//setProducts(data); //set state
});
使用嵌套的 fetch API 调用来获取产品 URL
如果您想详细了解产品图片URL,那么您可以使用wordpress 媒体url 端点来获取featured_image 的featured_image url 的woo-commerce 产品。
将此代码添加到您的 fetch 请求中。首先获取所有products 和featured_media 然后循环遍历它并获取所有source_url - 您可以将基于产品ID 的URL 保存在new array 中的react 状态中
fetch(state.source.api + "/wp/v2/product")
.then((response) => response.json())
.then((data) => {
//setProducts(data); //set state
//loop through each data to get featured_media number
data.forEach((x) => {
//get all urls using featured_media
fetch(state.source.api + "/wp/v2/media/"+x.featured_media)
.then((response) => response.json())
.then((o) => {
//get all urls OR store to react State
console.log(o.source_url)
});
})
});