我在一个React应用程序中使用。我正在尝试访问Rest中的产品特色图像。它已经提供了featured_media id,例如:featured_media: 15195,但这并不能真正帮助我显示图像。我一直试图找出如何在Rest中添加一个字段来返回产品图像URL。
有没有办法做到这一点,或资源,将是有帮助的?
发布于 2020-09-25 13:31:53
您可以使用两个选项--要么可以修改当前产品的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(state.source.api + "/wp/v2/product")
.then((response) => response.json())
.then((data) => {
//setProducts(data); //set state
});使用嵌套的fetch API调用来获取产品URL
如果您需要更多关于详细信息的产品映像URL,那么您可以使用wordpress媒体url端点获取woo-commerce产品的featured_image url。
将此代码添加到fetch请求中。首先获取所有的products和featured_media,然后循环它并获得所有的source_url -您可以根据产品id保存react状态中的new array中的urls。
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)
});
})
});https://stackoverflow.com/questions/64057237
复制相似问题