真实示例:客户购买了以下产品:
我的客户使用的是表费率运费插件,它只能使用购物车总重量来计算运费,在这种情况下,它是3.0公斤。
但真正的可充电重量只有2.6公斤......
已经四处搜索,找不到任何功能来计算特定运费等级的购物车物品重量小计,所以刚刚起草了以下功能,但似乎无效。有人可以帮助改善这个功能吗?
// calculate cart weight for certain shipping class only
if (! function_exists('get_cart_shipping_class_weight')) {
function get_cart_shipping_class_weight() {
$weight = 0;
foreach ( $this->get_cart() as $cart_item_key => $values ) {
if ( $value['data']->get_shipping_class() == 'shipping-from-XX' ) {
if ( $values['data']->has_weight() ) {
$weight += (float) $values['data']->get_weight() * $values['quantity'];
}
}
return apply_filters( 'woocommerce_cart_contents_weight', $weight );
}
}
}
// end of calculate cart weight for certain shipping class
答案 0 :(得分:0)
更新(错字错误已更正)。
要使其工作,您需要以这种方式在自定义钩子函数中使用专用的woocommerce_cart_contents_weight
过滤器钩子:
add_filter( 'woocommerce_cart_contents_weight', 'custom_cart_contents_weight', 10, 1 );
function custom_cart_contents_weight( $weight ) {
$weight = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
if ( $product->get_shipping_class() == 'shipping-from-XX' && $product->has_weight() ) {
$weight += (float) $product->get_weight() * $cart_item['quantity'];
}
}
return $weight;
}
代码放在活动子主题(或活动主题)的function.php文件中。它现在应该有效。
答案 1 :(得分:0)
感谢@Loic TheAztec,只需要删除额外的" - >",也许是你的拼写错误,然后一切都运作完美,归功于@LoicTheAztec!所以正确的代码应该如下:
//Alter calculated cart items total weight for a specific shipping class
add_filter( 'woocommerce_cart_contents_weight', 'custom_cart_contents_weight', 10, 1 );
function custom_cart_contents_weight( $weight ) {
$weight = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
if ( $product->get_shipping_class() == 'shipping-from-xx' && $product->has_weight() ) {
// just remember to change this above shipping class name 'shipping-from-xx' to the one you want, use shipping slug
$weight += (float) $product->get_weight() * $cart_item['quantity'];
}
}
return $weight;
}