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

基于商品分类添加订单号前缀的函数对可变商品失效

WooCommerce 变体商品订单前缀修复方案

你的问题出在WooCommerce商品变体默认不继承父商品的产品分类,当前代码用变体ID调用has_term时,无法检测到父商品上的example-4分类,导致无法添加对应前缀。

修改后的代码会优先检查变体自身的分类,若不存在则使用父商品ID进行分类检测:

function filter_woocommerce_order_number( $order_number, $order ) {
    // 遍历订单商品(每单仅1件商品)
    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        
        // 优先获取父商品ID(如果是变体)
        $check_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

        // 匹配分类并添加对应前缀
        if ( has_term( array( 'example-1', 'example-2', 'example-3', 'example-4' ), 'product_cat', $check_id ) ) {
            return 'UF-' . $order_number;
        } elseif ( has_term( array( 'example-5' ), 'product_cat', $check_id ) ) {
            return 'UH-' . $order_number;
        } elseif ( has_term( array( 'example-6' ), 'product_cat', $check_id ) ) {
            return 'UT-' . $order_number;
        } elseif ( has_term( array( 'example-7' ), 'product_cat', $check_id ) ) {
            return 'HP-' . $order_number;
        }
    }
    
    return $order_number;
}
add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );

关键改动说明

  1. 直接获取商品对象$product = $item->get_product(),通过is_type('variation')精准判断是否为变体商品
  2. 使用get_parent_id()获取父商品ID作为分类检测的目标ID,确保能读取到父商品上的example-4分类
  3. 简化ID判断逻辑,避免因变体ID导致的分类检测失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:30:47