Splitting Woocommerce by Quantity

  Kiến thức lập trình

I currently have found the following code to split items into separate shipping packages in woocommerce

add_filter( 'woocommerce_cart_shipping_packages', 'bbloomer_split_shipping_packages_by_class' );
 
function bbloomer_split_shipping_packages_by_class( $packages ) {
       
   $destination = $packages[0]['destination'];  
   $user = $packages[0]['user']; 
   $applied_coupons = $packages[0]['applied_coupons'];
   $packages = array();
    
   foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {    
      $key = $cart_item['data']->get_shipping_class_id();
      $packages[$key]['contents'][$cart_item_key] = $cart_item;
   }
    
   foreach ( $packages as $index => $package ) {
      $total = array_sum( wp_list_pluck( $packages[$index]['contents'], 'line_total' ) );
      $packages[$index]['destination'] = $destination;
      $packages[$index]['user'] = $user;
      $packages[$index]['applied_coupons'] = $applied_coupons;
      $packages[$index]['contents_cost'] = $total;
   }
 
   return $packages;
}

However, I am also trying to split packages that have items with multiple quantity into separate packages too. OR Multiply the shipping rate cost by the quantity
Is it possible to modify the above code to achieve this?

Thanks

I tried

add_filter( 'woocommerce_package_rates', 'shipping_cost_based_on_number_of_items', 10, 2 );
function shipping_cost_based_on_number_of_items( $rates, $package ) {
    $numer_of_items = (int) sizeof($package['contents']);

    // Loop through shipping rates
    foreach ( $rates as $rate_key => $rate ){
            $has_taxes = false;

            // Set the new cost
            $rates[$rate_key]->cost = $rate->cost * $numer_of_items;

            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $tax > 0 ){
                    // New tax calculated cost
                    $taxes[$key] = $tax * $numer_of_items;
                    $has_taxes = true;
                }
            }
            // Set new taxes cost
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;
       
    }
    return $rates;
}

However this did not work

New contributor

user24331075 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT