首页 文章

更改Woocommerce中特定运输类别的购物车商品总重量

提问于
浏览
2

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

  • 产品A,重量:0.2kg,数量:2,发货类别:免运费

  • 产品B,重量:0.6kg,数量:3,发货类别:重量基础运费

  • 产品C,重量:0.8kg,数量:1,发货类别:重量基础运费

我的客户使用的是表费率运费插件,它只能通过使用总购物车内容重量来计算运费,在这种情况下它是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

2 回答

  • 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文件中 . 它应该现在有效 .

  • 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;
     }
    

相关问题