WooCommerce – Flat rate shipping based on X quantity steps?

For that, you need to use a hooked function in woocommerce_package_rates filter hook, targeting “Flat rate” shipping method.

In shipping settings for flat rate shipping method you will set a cost of 5.

Each 5 items step, the shipping cost will be increased by 5:
• From 1 to 5 Items: Delivery = 5
• From 6 to 10 Items: Delivery = 10
• From 11 to 15 Items: Delivery = 15
And so on…

Here is the code:

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

    $items_count  = WC()->cart->get_cart_contents_count(); // Cart item count
    $items_change = 5; // number of items needed to increase the cost each time
    $rate_operand = ceil( $items_count / $items_change ); // Operand increase each 5 items here

    foreach ( $rates as $rate_key => $rate ){
        // Targetting "Flat rate"
        if( 'flat_rate' === $rate->method_id ) {
            $has_taxes = false;

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

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

Code goes in function.php file of your active child theme (or active theme). tested and works.

Refresh the shipping caches: (required)

  1. This code is already saved on your active theme’s function.php file.
  2. The cart is empty
  3. In a shipping zone settings, disable / save any shipping method, then enable back / save.

Leave a Comment