首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WP中获取基于WooCommerce产品URL的featured_image

在WP中获取基于WooCommerce产品URL的featured_image
EN

Stack Overflow用户
提问于 2020-09-25 03:08:14
回答 1查看 1.4K关注 0票数 2

我在一个React应用程序中使用。我正在尝试访问Rest中的产品特色图像。它已经提供了featured_media id,例如:featured_media: 15195,但这并不能真正帮助我显示图像。我一直试图找出如何在Rest中添加一个字段来返回产品图像URL。

有没有办法做到这一点,或资源,将是有帮助的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-25 13:31:53

您可以使用两个选项--要么可以修改当前产品的rest api URL,以便在一个调用中返回图像url,要么可以通过添加下面的代码来修改functions.php

修改functions.php

代码语言:javascript
复制
//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之后使用以下单个请求

代码语言:javascript
复制
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请求中。首先获取所有的productsfeatured_media,然后循环它并获得所有的source_url -您可以根据产品id保存react状态中的new array中的urls。

代码语言:javascript
复制
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)
      });
    })
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64057237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档