WooCommerce的woocommerce_product_get_weight钩子对产品变体无效
问题
我用woocommerce_product_get_weight钩子覆盖产品重量(用于影响运费计算),发现这个钩子对所有产品变体都不触发,但简单产品正常触发。从代码里能看到,函数调用时会写日志,但变体产品没有日志输出,只有简单产品有。现在想确认这是不是实现需求的正确方式,求解决方案。
我的代码如下:
function custom_weight($weight, $product) { logvar($weight, "weight before"); logvar($product, "variant terms - weight"); if (!is_admin()) { $product_id = $product->get_id(); if (has_term('weight-sheer', 'product_tag', $product_id)) $weight = 1.5/16; elseif (has_term('weight-light', 'product_tag', $product_id)) $weight = 7.5/16; elseif (has_term('weight-medium', 'product_tag', $product_id)) $weight = 12/16; elseif (has_term('weight-heavy', 'product_tag', $product_id)) $weight = 30/16; elseif (has_term('Thread', 'product_cat', $product_id)) $weight = 0; elseif (has_term('Gift Cards', 'product_cat', $product_id)) $weight = 0; } logvar($weight, "weight after"); return $weight; } add_filter('woocommerce_product_get_weight', 'custom_weight', 25, 2); //helper function for easy logging function logvar($var, $label = null) { if ($label != null) { wc_get_logger()->debug($label, array('source' => 'mylog')); } wc_get_logger()->debug(var_export($var, true), array('source' => 'mylog')); }
解决方案
- WooCommerce中,变体产品有独立的重量获取钩子
woocommerce_product_variation_get_weight,woocommerce_product_get_weight仅对简单产品生效,这就是变体无日志输出的核心原因。 - 直接将同一个处理函数绑定到两个钩子上,就能同时覆盖简单产品和变体产品的重量计算逻辑。
- 优化
has_term的判断逻辑:变体产品的标签/分类通常继承自父产品,直接用变体ID检测可能失效,建议改用产品对象作为has_term的第三个参数,它会自动处理继承关系,确保标签/分类判断准确。
修改后的代码如下:
function custom_weight($weight, $product) { logvar($weight, "weight before"); logvar($product, "variant terms - weight"); if (!is_admin()) { // 用产品对象检测分类/标签,兼容变体和简单产品的继承逻辑 if (has_term('weight-sheer', 'product_tag', $product)) $weight = 1.5/16; elseif (has_term('weight-light', 'product_tag', $product)) $weight = 7.5/16; elseif (has_term('weight-medium', 'product_tag', $product)) $weight = 12/16; elseif (has_term('weight-heavy', 'product_tag', $product)) $weight = 30/16; elseif (has_term('Thread', 'product_cat', $product)) $weight = 0; elseif (has_term('Gift Cards', 'product_cat', $product)) $weight = 0; } logvar($weight, "weight after"); return $weight; } // 同时绑定简单产品和变体产品的重量钩子 add_filter('woocommerce_product_get_weight', 'custom_weight', 25, 2); add_filter('woocommerce_product_variation_get_weight', 'custom_weight', 25, 2); //helper function for easy logging function logvar($var, $label = null) { if ($label != null) { wc_get_logger()->debug($label, array('source' => 'mylog')); } wc_get_logger()->debug(var_export($var, true), array('source' => 'mylog')); }
补充说明
- 钩子优先级设为25是合理的,确保晚于默认逻辑执行,能有效覆盖原有重量值。
- 如果变体产品有独立设置的标签/分类,上述代码也能正确检测;如果是继承父产品的属性,
has_term传入产品对象时会自动读取父产品的分类标签,无需额外处理。
内容的提问来源于stack exchange,提问作者Venk Reddy
相关产品推荐
相关产品推荐

