【问题标题】:Get WooCommerce product URL based featured_image in WP Rest API在 WP Rest API 中获取基于 WooCommerce 产品 URL 的 features_image
【发布时间】:2021-01-11 09:11:57
【问题描述】:

我在 React 应用程序中使用 WP Rest API。我正在尝试访问 Rest API 中的产品特色图片。它已经带有 features_media id,例如:featured_media: 15195,但这并不能真正帮助我显示图像。我一直在试图弄清楚如何在 Rest API 中添加一个字段以返回产品图片 URL。

有没有办法做到这一点,或者有什么有用的资源?

【问题讨论】:

  • 您使用什么端点来检索产品?还是产品?您是否只是想使用 rest api 获取单个产品图像/
  • 我正在使用/wp/v2/product?per_page=100获取所有产品,不到100个
  • 尝试使用 => http://yoururl/wp-json/wc/v3/products/ - 这将为您提供包含每个 products_Images 的数组中的所有产品数据。
  • 我收到 ``` 代码“woocommerce_rest_cannot_view”消息“抱歉,您无法列出资源。”数据状态 401 ``` 我没有设置 Woocommerce 部分,其他人做了,有什么我应该登录的吗?我虽然登录到 WP 网站
  • 您使用的是基本身份验证吗?

标签: javascript reactjs wordpress woocommerce


【解决方案1】:

您有两个可以使用的选项 - 您可以修改您当前的产品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_imagefeatured_image url 的woo-commerce 产品。

将此代码添加到您的 fetch 请求中。首先获取所有productsfeatured_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)
      });
    })
});

【讨论】:

    猜你喜欢
    • 2014-11-06
    • 2022-01-01
    • 2019-03-03
    • 2016-11-19
    • 2017-11-20
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多