看来我一直用来覆盖产品重量(为了影响运费计算)的 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_product_get_weight
是WC_Product
get_weight()
方法的复合过滤钩,但对于产品变化,您必须另外使用woocommerce_product_variation_get_weight
过滤钩。
此外,由于产品变体不处理 WooCommerce 产品类别或标签,因此您需要获取父变量产品 ID 才能使其与 WordPress
has_term()
功能配合使用,例如:
add_filter( 'woocommerce_product_get_weight', 'filter_product_weight', 10, 2 );
add_filter( 'woocommerce_product_variation_get_weight', 'filter_product_weight', 10, 2 );
function filter_product_weight( $weight, $product ) {
if ( is_admin() ) {
return $weight;
}
$product_id = $product->is_type('variation') ? $product->get_parent_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;
}
if ( has_term(array('Thread', 'Gift Cards'), 'product_cat', $product_id) ) {
$weight = 0;
}
return $weight;
}
现在它将适用于所有产品类型,包括产品变体。