首页 > 解决方案 > Woocommerce 向商品和购物车添加运输重量

问题描述

我试图添加

  1. 购物车中每件物品重量为 51 克,类别为“shipping-class-jewelry”
  2. 添加内容物的包装重量。所以它的工作原理是每 2 件物品的运费为 54 克,因为盒子(运输箱)可以存放 2 件。

我遇到的问题是

  1. 我无法遍历购物车项目,foreach 循环只运行一次

  2. 我不知道如何获得每件物品的运输类 slug

  3. 最后不知道怎么设置推车的重量

  4. 我不确定要使用哪个钩子。我知道它应该是一个动作而不是过滤器,但我们需要在购买之后但在数据存储到数据库之前完成它。这是因为我很喜欢 DHL for Woocommerce 插件,它使用购物车重量自动生成标签。如果打印错误,DHL 在商店不接受包裹。

        // define the callback 
    function action_woocommerce_review_order_before_submit() { 
        $jewelry_box = 0.051; //51 grams
        $quantity = 0; //number of items of that particular class
        $dhl_box_number = 0;//number of shipping boxes. Each box can have 2 items.
        $dhl_box_weight = 0.054; //54 grams for the shipping box
        $dhl_external_weight = 0.0; // dhl box weight * number of boxes needed for packaging
        $weight = 0.0;// for the final weight
        
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ){
            
            if($cart_item->get_shipping_class_id() == "shipping-class-jewelry" ) { //this line is causing a critical error
                $quantity += 1; 
                $weight += $jewelry_box+ $cart_item->get_weight(); //now the weight should be the items weight + 51 grams, which is the box it comes in
            }//endif
            
        }//endfor
        
        if ($quantity % 2 == 0) { //if is even
            $dhl_box_number = ($quantity / 2);
        } else if($quantity % 2 == 1) {// if is odd
            $dhl_box_number = (($quantity / 2)+1);
        }

        $dhl_external_weight = $dhl_box_weight * $dhl_box_number;
        $weight +=  $dhl_external_weight;
        
        //echo($weight);*/
        
    }; 
             
    // add the action 
    add_action( 'woocommerce_review_order_before_submit','action_woocommerce_review_order_before_submit', 10, 1 ); 

标签: phpwordpresswoocommercehook-woocommercedhl

解决方案


推荐阅读