Home » WooCommerce: Flat Rate Calculation Based on Weight (Without a Plugin!)

WooCommerce: Flat Rate Calculation Based on Weight (Without a Plugin!)

by Tutor Aspire

We already talked about weight based shipping and in this post we found out how to charge different flat rates based on shipping weight thresholds.

But now I want to show you how you can use the default “Flat Rate” to calculate shipping costs based on cart weight, thanks to a multiplier. For example, your shipping rate might be “$5 for each Kg” – as you know the default “Flat Rate” only allows you to define one rate e.g. $10.

So, what if you want to calculate shipping charges by weight? Well, here’s a simple workaround for you.

Shipping by Weight: first of all create a new “Flat Rate” with cost = 0 and get its ID

PHP snippet: Turn Flat Rate into a Weight Multiplier Shipping Rate

Before getting into coding, a few notes first. The following snippet won’t work unless you:

  • enter weight for every product in your store
  • create a Flat Rate and get its ID (“84” in the example below)
  • define your shipping by weight formula ($5 multiplied by rounded kilos in the example below. My snippet will return $5 if cart weight is 1.4Kg, $10 if cart weight is 1.6Kg, $15 if cart weight is 3.1Kg and so on… Adjust as per your project specifications)

The following snippet might not fully work if the Flat Rate is taxable and if you have tax enabled in your store. It might need a little tweak to make it work.

Also make sure to empty your Cart before testing – every time you work with shipping rates you need to clear your “session” and emptying the Cart should trigger that automatically.

/**
 * @snippet       Flat Rate = Shipping by Weight
 * @how-to        Get tutoraspire.com FREE
 * @sourcecode    https://tutoraspire.com/?p=114302
 * @author        Tutor Aspire
 * @compatible    WooCommerce 3.5.4
 * @donate $9     https://tutoraspire.com
 */

add_filter( 'woocommerce_package_rates', 'tutoraspire_woocommerce_tiered_shipping', 999, 2 );
   
function tutoraspire_woocommerce_tiered_shipping( $rates, $package ) {   
  $cart_weight = WC()->cart->cart_contents_weight;
  if ( isset( $rates['flat_rate:84'] ) ) {
  $rates['flat_rate:84']->cost = 5 * round ( $cart_weight ); 
}
  return $rates;
}

You may also like