Halloween Sale 15% off Ends in See the plans
PHP

Weight-Based Flat Rate Shipping Cost

Recalculates your Flat Rate shipping price from the parcel weight using tiers you set, for example 4.95 up to 2 kg and 7.95 up to 10 kg.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_weight_tiers = array( // Max weight => cost.
    2  => 4.95,
    5  => 6.50,
    10 => 7.95,
);
$wpide_weight_extra = 0.50; // Cost per weight unit above the last tier.

add_filter( 'woocommerce_package_rates', function ( $rates, $package ) use ( $wpide_weight_tiers, $wpide_weight_extra ) {
    $weight = 0.0;

    foreach ( (array) $package['contents'] as $item ) {
        $weight += (float) $item['data']->get_weight() * (int) $item['quantity'];
    }

    ksort( $wpide_weight_tiers );
    $cost = null;

    foreach ( $wpide_weight_tiers as $max => $price ) {
        if ( $weight <= $max ) {
            $cost = $price;
            break;
        }
    }

    if ( null === $cost ) {
        $last = array_key_last( $wpide_weight_tiers );
        $cost = $wpide_weight_tiers[ $last ] + ceil( $weight - $last ) * $wpide_weight_extra;
    }

    foreach ( $rates as $rate ) {
        if ( 'flat_rate' !== $rate->get_method_id() ) {
            continue;
        }

        $old = (float) $rate->get_cost();
        $rate->set_cost( $cost );

        if ( $old > 0 && $rate->get_taxes() ) {
            $taxes = array();

            foreach ( $rate->get_taxes() as $key => $tax ) {
                $taxes[ $key ] = $tax * $cost / $old;
            }

            $rate->set_taxes( $taxes );
        }
    }

    return $rates;
}, 20, 2 );

Notes

Weights use your store's weight unit, and above the last tier the extra cost is added for every unit over it.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.