在 Woocommerce 中针对特定运输 class 更改计算的购物车商品总重量

Alter calculated cart items total weight for a specific shipping class in Woocommerce

真实示例:客户在购物车中购买了以下产品:

  1. 产品 A,重量:0.2kg,数量:2,运费 class:包邮
  2. 产品 B,重量:0.6 千克,数量:3,运费 class:基于重量的运费
  3. 产品 C,重量:0.8kg,数量:1,运费class:基于重量的运费

我的客户使用的是 table 运费插件,它只能使用购物车内容的总重量来计算运费,在本例中为 3.0kg。

但实际计费重量只有2.6kg...

四处搜索,找不到任何函数来计算特定运费的购物车商品重量小计 class,所以刚刚起草了以下函数,但它似乎不起作用。有人可以帮助改进这个功能吗?

// 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

更新(拼写错误已更正).

要使其正常工作,您需要以这种方式在自定义挂钩函数中使用专用 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 文件。现在应该可以使用了。

感谢@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;
 }