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

WooCommerce商品变体SKU生成函数失效排查求助

修复WooCommerce变体SKU自动生成问题

问题分析

你的代码存在几个关键问题导致SKU无法正常生成:

  1. 钩子参数不匹配:woocommerce_save_product_variation钩子实际传递2个参数($variation_id和$i),但你的函数只声明了1个参数,可能导致执行异常。
  2. 属性获取不准确:get_attribute()返回的是属性的显示名称(可能包含空格或格式化文本),而非原始属性值,容易导致匹配失败。
  3. 缺少错误调试:没有输出关键变量的状态,无法排查前缀、属性值是否正确获取。

修复后的代码

// *START -- Generate Product Variation SKUS

// Function to auto generate SKU
function generate_sku($variation_id, $i) {
    // 获取变体对象,先验证是否有效
    $product = wc_get_product($variation_id);
    if (!$product || !$product->is_type('variation')) {
        return;
    }

    // 更简洁的ACF前缀获取逻辑
    $prefix = get_field('sku_prefixes_space_gray', $variation_id) ?: 
              get_field('sku_prefixes_silver', $variation_id) ?: 
              get_field('sku_prefixes_gold', $variation_id);

    // 只有获取到前缀才继续
    if (empty($prefix)) {
        // 调试:如果没有前缀,记录日志或输出(生产环境建议注释)
        error_log("No SKU prefix found for variation ID: {$variation_id}");
        return;
    }

    // 获取变体的原始属性值(推荐用这个替代get_attribute)
    $attributes = $product->get_variation_attributes();
    
    // 处理内存属性
    $ram_size = isset($attributes['pa_memory']) ? $attributes['pa_memory'] : '';
    // 适配属性slug和显示名称两种格式
    $ram_size = str_replace(['gb-ram', 'GB RAM'], 'M', $ram_size);

    // 处理存储属性
    $drive_size = isset($attributes['pa_storage']) ? $attributes['pa_storage'] : '';
    $drive_sizes_map = [
        '1tb-ssd' => '1024S',
        '2tb-ssd' => '2048S',
        '4tb-ssd' => '4096S',
        '8tb-ssd' => '8192S',
    ];
    // 先匹配slug,匹配失败再处理GB格式
    if (isset($drive_sizes_map[$drive_size])) {
        $drive_size = $drive_sizes_map[$drive_size];
    } else {
        $drive_size = str_replace(['gb-ssd', 'GB SSD'], 'S', $drive_size);
    }

    // 处理成色属性
    $condition = isset($attributes['pa_condition']) ? $attributes['pa_condition'] : '';
    $conditions_map = [
        'mint' => 'CR',
        'grade-a' => 'CRG',
        'grade-b' => 'EX',
        'grade-c' => 'AV',
    ];
    $condition = isset($conditions_map[$condition]) ? $conditions_map[$condition] : $condition;

    // 生成SKU
    $new_sku = sprintf('%s_%s%s_%s', $prefix, $ram_size, $drive_size, $condition);
    
    // 仅当SKU有变化时才保存,避免重复操作
    if ($product->get_sku() !== $new_sku) {
        $product->set_sku($new_sku);
        $saved = $product->save();
        // 调试:检查保存是否成功
        if (!$saved) {
            error_log("Failed to save SKU {$new_sku} for variation ID: {$variation_id}");
        }
    }
}

// 修正钩子参数数量,确保传递2个参数
add_action('woocommerce_save_product_variation', 'generate_sku', 10, 2);

// *END -- Generate Product Variation SKUS

关键优化点

  • 参数匹配:修正钩子的参数接收数量,确保函数能正确触发。
  • 属性获取:使用get_variation_attributes()获取原始属性slug,避免显示名称的格式干扰。
  • 调试日志:添加error_log()记录异常情况,方便排查问题。
  • 避免重复保存:只有当SKU实际变化时才执行保存操作,提升性能。
  • ACF逻辑简化:使用PHP的?:运算符简化前缀判断,代码更简洁。

额外排查建议

  1. 确认ACF字段确实附加在产品变体上,而非父产品。如果字段在父产品上,需要将$variation_id替换为父产品ID:$parent_id = $product->get_parent_id();,然后用get_field('字段名', $parent_id)获取。
  2. 检查属性slug是否与代码中的pa_memory、pa_storage、pa_condition完全一致,可在WooCommerce属性设置页面查看。
  3. 启用WordPress调试模式(wp-config.php中设置WP_DEBUG=true),查看是否有PHP错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:45:07