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

使用WooCommerce API无法将产品分配至对应分类/子分类

解决WooCommerce API按分类名称匹配分配产品的问题

核心思路

WooCommerce产品API要求分类字段必须传入ID而非名称,所以需要先拉取站点所有多级分类,构建「分类名称→分类ID」的映射表,创建产品时通过名称查表得到对应ID再传入。

具体实现步骤

1. 构建分类名称-ID映射表

添加函数拉取所有分类(处理分页)并生成映射:

async function getCategoryNameIdMap(woocommerce) {
  const categoryMap = new Map();
  let page = 1;
  let hasMore = true;

  while (hasMore) {
    try {
      const response = await woocommerce.get("products/categories", {
        page,
        per_page: 100,
        orderby: "name",
        order: "asc"
      });

      response.data.forEach(category => {
        categoryMap.set(category.name, category.id);
      });

      const totalPages = parseInt(response.headers["x-wp-totalpages"]);
      hasMore = page < totalPages;
      page++;
    } catch (error) {
      console.error("拉取分类失败:", error);
      hasMore = false;
    }
  }

  return categoryMap;
}

2. 修改产品创建逻辑

提前获取映射表,根据category_path的名称匹配对应ID:

const WooCommerce = new WooCommerceAPI({
  url: "https://X.X/",
  consumerKey: "ck_X",
  consumerSecret: "cs_X0",
  wpAPI: true,
  version: "wc/v3",
});

await createCategories(WooCommerce);
// 预加载分类名称-ID映射
const categoryMap = await getCategoryNameIdMap(WooCommerce);

for (let i = 0; i < searchResults.products.length; i++) {
  const product = searchResults.products[i];
  const detailsData = await details(apiKey, product.id);

  const categoryPath = detailsData.category_path;
  const productCategories = [];

  // 遍历分类路径数组,匹配对应ID
  for (const section of categoryPath) {
    const categoryId = categoryMap.get(section.name);
    if (categoryId) {
      productCategories.push({ id: categoryId });
    } else {
      console.warn(`未找到分类 "${section.name}" 的ID,跳过该分类`);
    }
  }

  const productData = {
    name: product.title,
    type: "simple",
    categories: productCategories.length > 0 ? productCategories : [{ id: 0 }]
  };
  
  try {
    await WooCommerce.post("products", productData);
    console.log(`产品 "${product.title}" 创建成功`);
  } catch (error) {
    console.error(`创建产品 "${product.title}" 失败:`, error);
  }
}

注意事项

  • 若存在同名不同层级的分类,可将映射键改为组合路径(如父分类名称/子分类名称),避免匹配错误。
  • 确保createCategories执行完成后再获取映射表,避免遗漏新创建的分类。
  • 拉取分类时通过分页参数覆盖所有分类,防止因分类数量过多导致遗漏。

内容的提问来源于stack exchange,提问作者Just simple Patrick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:12:26