使用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
相关产品推荐
相关产品推荐

