1
votes

In Woocommerce I have installed a shipping plug in but it calculates shipping per item in cart instead of per order total.

What I need is to calculate the shipping cost this way: - First kg is $5 - And $1 by kilo for all others.

Is it possible to do it?

With the plugin if there is 2 items in cart of 1 kg each, it calculates the shipping as 2 x $5 = $10
Instead what I should need is: $5 (first kilo) + $1 (additional kilo) = $6 (for 2 kg).

I have no response from plugin developer, so looking for work around.

1
Could you show what you have tried as your work around?MinistryOfChaps
I am asking for work around or solution. I am asking for code to add to my plugin.php so that cart is submitted as combined total. thank youlinda
oops, what happened to my question - someone edited it? I cannot make sense of the edit now. I want to know how to get my plugin to calculate the shipping based on total weight in the cart instead of on each product in the cart....linda

1 Answers

1
votes

UPDATED: You don't need any plugin (so you can remove it).

To get a shipping rate calculated on total cart weight, with:

  • an initial amount of $5 (for the first kilo)
  • a variable rate of $1 for each additional kilo

Do the following:

1) Settings in WooCommerce:
For all your "Flat rate" shipping method (in each shipping zone), set a cost of 1 (amount by kilo).

enter image description here

So the cost

(Once done disable/save and enable/save to refresh woocommerce transient cache)

2) Custom code (as the shipping unit cost is $1 by kilo, we add 4 kilos to total cart weight in the calculations to set the correct cost):

add_filter( 'woocommerce_package_rates', 'custom_delivery_flat_rate_cost_calculation', 10, 2 );
function custom_delivery_flat_rate_cost_calculation( $rates, $package )
{
    // The total cart items  weight
    $cart_weight = WC()->cart->get_cart_contents_weight();

    foreach($rates as $rate_key => $rate_values){
        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;
        if ( 'flat_rate' === $method_id ) {
            ##  SHIPPING COSTS AND TAXES CALCULATIONS ##
            $rates[$rate_id]->cost = $rates[$rate_id]->cost*($cart_weight+4);
            foreach ($rates[$rate_id]->taxes as $key => $tax){
                if( $rates[$rate_id]->taxes[$key] > 0 ){
                    $tax_cost = number_format( $rates[$rate_id]->taxes[$key]*($cart_weight+4));
                    $rates[$rate_id]->taxes[$key] = $tax_cost;
                }
            }
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on woocommerce versions 2.6.x and 3+