Progressive cart item custom shipping cost in Woocommerce

I need to figure out a way to do woocommerce shipping rates based on items on cart. I need to charge 120 if buying 1-2 items and 180 buying 3. I added a free shipping option for 4+ (based on $)

I tried adding this to the flat rate price: 120+60([qty]-2) it works in all instances but the 1 item, because it charges $60.

Any thoughts?

Upvotes: 1

Views: 559

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253804

With the following code, you will be able to get this shipping rates:
- 1 or 2 items: $120
- 3 items: $180
- 4 items or more: Free shipping (hiding flat rate method)

1) Add the following code to function.php file of your active child theme (active theme):

add_filter('woocommerce_package_rates', 'custom_progressive_shipping_costs', 10, 2);
function custom_progressive_shipping_costs( $rates, $package ){

    $items_count  = WC()->cart->get_cart_contents_count();

    if( $items_count < 3 ){
        $cost_rate = 2;
    } else {
        $cost_rate = $items_count;
    }

    foreach ( $rates as $rate_key => $rate ){
        $taxes = [];
        $has_taxes = false;
        // Targeting "flat rate"
        if ( 'flat_rate' === $rate->method_id ) {
            // For 1, 2 or 3 items
            if ( $items_count <= 3 ) {
                $rates[$rate_key]->cost = $rate->cost * $cost_rate;

                // Taxes rate cost (if enabled)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $tax > 0 ){
                        $has_taxes = true;
                        $taxes[$key] = $tax * $cost_rate;
                    }
                }
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
            // For more than 3 hide Flat rate
            else {
                // remove flat rate method
                unset($rates[$rate_key]);
            }
        }
    }
    return $rates;
}

And save…

2) In Your shipping method settings, you will need to set 60 as your "Flat rate" cost and SAVE.

You need to keep your minimal amount for "Free shipping" method.

You are done. Tested and works.

Upvotes: 4

Related Questions