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

如何修改PHP脚本通过REST API将JSON的父子分类导入WooCommerce

操作前置说明

首先修正你提供的JSON格式问题:两处缺失逗号,分别是"SKU": "427515"行末尾、"full_category": "souvenirs and gifts"行末尾,否则PHP无法正常解析JSON内容。

修改核心逻辑
  • 替换原脚本中读取不存在的categorias字段的逻辑,改为提取JSON中full_category(父分类)和category(子分类)的关联对并去重
  • 分类创建时先处理父分类:父分类不存在则创建,获取到父分类ID后再处理子分类,创建子分类时绑定父分类ID
  • 商品关联分类时同时绑定父分类和子分类ID,也可根据业务需要仅绑定子分类ID
  • 修复原脚本中函数调用大小写不匹配、JSON字段名大小写不匹配的问题
修改后完整代码
// 提取所有唯一的父子分类关联对
function getCategories()
{
    $products = getJsonFromFile();
    $categoryPairs = [];
    foreach ($products as $product) {
        // 组装父子分类对,用拼接字符串去重避免重复处理
        $pairKey = $product['full_category'] . '|' . $product['category'];
        $categoryPairs[$pairKey] = [
            'parent' => $product['full_category'],
            'child' => $product['category']
        ];
    }
    return array_values($categoryPairs);
}

// 按分类名称和父ID获取分类ID,避免同名字分类冲突
function getCategoryIdByName($categoryName, $parentId = 0)
{
    $woocommerce = getWoocommerceConfig();
    // 分页获取全部分类,避免分类数量多的时候漏判
    $page = 1;
    do {
        $categories = $woocommerce->get('products/categories', ['page' => $page, 'per_page' => 100]);
        foreach ($categories as $category) {
            if ($category['name'] == $categoryName && $category['parent'] == $parentId) {
                return $category['id'];
            }
        }
        $page++;
    } while (count($categories) > 0);
    return false;
}

// 判断分类是否存在,支持按父ID筛选
function checkCategoryByName($categoryName, $parentId = 0)
{
    return (bool)getCategoryIdByName($categoryName, $parentId);
}

// 创建父子关联分类
function createCategories()
{
    $categoryPairs = getCategories();
    $woocommerce = getWoocommerceConfig();
    
    foreach ($categoryPairs as $pair) {
        // 先处理父分类
        $parentId = getCategoryIdByName($pair['parent']);
        if (!$parentId) {
            $parentData = [
                'name' => $pair['parent']
            ];
            $parentRes = $woocommerce->post('products/categories', $parentData);
            $parentId = $parentRes['id'];
        }

        // 再处理子分类,绑定父ID
        if (!checkCategoryByName($pair['child'], $parentId)) {
            $childData = [
                'name' => $pair['child'],
                'parent' => $parentId
            ];
            $woocommerce->post('products/categories', $childData);
        }
    }
}

// 创建商品并关联分类
function createProducts()
{
    $woocommerce = getWoocommerceConfig();
    $products = getJsonFromFile();

    $imgCounter = 0;
    foreach ($products as $product) {
        // 按SKU判断商品是否已存在,注意JSON中SKU为大写
        $productExist = checkProductBySku($product['SKU']);
        if ($productExist) {
            // 可根据需要添加更新逻辑,这里跳过已存在商品
            continue;
        }
        
        $categoriesIds = [];
        // 获取父分类ID
        $parentId = getCategoryIdByName($product['full_category']);
        if ($parentId) {
            $categoriesIds[] = ['id' => $parentId];
        }
        // 获取子分类ID
        $childId = getCategoryIdByName($product['category'], $parentId);
        if ($childId) {
            $categoriesIds[] = ['id' => $childId];
        }

        // 组装商品其他字段,你可以根据JSON内容补充剩余字段
        $finalProduct = [
            'name' => $product['name'],
            'sku' => $product['SKU'],
            'description' => $product['description'],
            'regular_price' => (string)$product['price'],
            'categories' => $categoriesIds,
            // 可补充重量、尺寸等其他字段
            'dimensions' => [
                'length' => (string)$product['box_length'],
                'width' => (string)$product['box_width'],
                'height' => (string)$product['box_height']
            ]
        ];
        // 调用接口创建商品
        $woocommerce->post('products', $finalProduct);
    }
}
执行顺序

请先执行createCategories()完成所有分类的创建,再执行createProducts()导入商品,避免出现分类ID找不到的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:48:02