You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce REST API v3:一次性获取多个商品变体

针对WooCommerce变体批量获取价格的优化方案

方案1:使用官方批量请求接口

WooCommerce REST API支持批量请求,你可以把多个获取变体的请求打包成一个POST请求,一次完成所有查询,还能指定只返回需要的字段(id和price)来减少数据量。

Node.js代码示例:

const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;

const api = new WooCommerceRestApi({
  url: "你的店铺地址",
  consumerKey: "你的consumer key",
  consumerSecret: "你的consumer secret",
  version: "wc/v3"
});

// 准备要查询的变体ID数组
const variationIds = [123, 456, 789];

// 构造批量请求的参数
const batchRequests = variationIds.map(id => ({
  method: "GET",
  path: `/products/variations/${id}`,
  params: {
    fields: "id,price" // 只获取ID和价格,减少返回数据
  }
}));

// 发送批量请求
api.post("batch/products", { requests: batchRequests })
  .then(response => {
    // 处理返回结果,每个请求的结果在response.data.responses里
    const variationPrices = response.data.responses.map(res => ({
      id: res.data.id,
      price: res.data.price
    }));
    console.log(variationPrices);
  })
  .catch(error => {
    console.error(error.response.data);
  });

方案2:自定义REST API端点(效率最高)

如果有权限修改店铺的主题或插件,自己写一个自定义API端点,直接查询数据库获取变体价格,这是效率最高的方式,因为跳过了WooCommerce默认API的冗余逻辑。

  1. 在主题的functions.php里添加以下代码:
add_action('rest_api_init', function () {
  register_rest_route('custom/v1', '/variation-prices/', array(
    'methods' => 'POST',
    'callback' => 'get_batch_variation_prices',
    'permission_callback' => function () {
      // 这里可以添加权限验证,比如检查API密钥或者登录状态
      return current_user_can('manage_woocommerce');
    }
  ));
});

function get_batch_variation_prices($request) {
  $variation_ids = $request->get_param('variation_ids');
  if (!is_array($variation_ids)) {
    return new WP_Error('invalid_data', 'Variation IDs must be an array', array('status' => 400));
  }

  $prices = array();
  global $wpdb;
  foreach ($variation_ids as $id) {
    $price = $wpdb->get_var($wpdb->prepare(
      "SELECT meta_value FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = '_price'",
      $id
    ));
    if ($price !== null) {
      $prices[] = array(
        'id' => $id,
        'price' => $price
      );
    }
  }

  return rest_ensure_response($prices);
}
  1. 然后在Node.js里调用这个自定义端点:
api.post("custom/v1/variation-prices/", {
  variation_ids: [123, 456, 789]
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error(error.response.data);
});

方案3:批量获取产品并提取变体价格

如果你的产品数量不算特别多,可以一次性批量获取多个产品,指定只返回产品ID和变体数据,然后在本地提取变体价格,这种方式比单独请求每个变体要少很多请求。

Node.js代码示例:

// 准备要查询的产品ID数组(对应变体所属的产品)
const productIds = [78, 90, 102];

api.get("products", {
  include: productIds,
  per_page: 50, // 一次最多拿50个产品,WooCommerce默认上限是100
  fields: "id,variations" // 只返回产品ID和变体列表
})
.then(response => {
  const variationPrices = [];
  response.data.forEach(product => {
    product.variations.forEach(variation => {
      // 这里的variation对象已经包含id和price,直接提取
      variationPrices.push({
        id: variation.id,
        price: variation.price
      });
    });
  });
  console.log(variationPrices);
})
.catch(error => {
  console.error(error.response.data);
});

注意事项

  • 不管用哪种方案,都要尽量使用fields参数过滤返回字段,减少数据传输量,提升请求速度。
  • 批量请求的数量不要太多(比如控制在100以内),避免触发服务器的请求限制。

内容的提问来源于stack exchange,提问作者LAZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:51:10