HOMEBlogWooCommerce DevelopmentWooCommerce Shipping By Weight: 3 Easy Steps to…

WooCommerce Shipping By Weight: 3 Easy Steps to Restrict Shipping Methods by Order Weight

WooCommerce Shipping By Weight

A shipping method that works for a light order can become unsuitable or too costly as its weight increases. This guide shows you how to implement WooCommerce Shipping By Weight with a small custom plugin that removes selected methods when a package exceeds their limits.

The plugin filters existing rates for each shipping package; it does not create rates or calculate shipping prices. You will identify the exact method instances to restrict, keep a separate fallback available, and test the results at the weight boundaries. If an order is split into multiple packages, each package is evaluated independently.

  • WordPress and WooCommerce, administrator access, PHP 8.0 or later, and access to the site plugin directory.
  • A staging site and a current backup of both site files and the database.
  • A configured shipping zone with two methods to restrict and a separate, unrestricted fallback method available for the intended destination.
  • Products or variations with accurate, positive weights, and a known WooCommerce store weight unit.
  • A test shipping address that matches the intended zone and permission to activate a custom plugin.

Step 1: Define the weight rules and fallback

Before writing code, turn your shipping policy into limits for specific method instances, not every method of the same type. In this WooCommerce Shipping By Weight example, flat_rate instance 12 is eligible for packages up to and including 10 kg, while local_pickup instance 15 is eligible up to and including 20 kg. These identifiers are illustrative: replace them with the actual instances in your store. The filter will remove each restricted rate above its limit or when the package weight cannot be determined.

Configure a distinct, unrestricted fallback, such as flat_rate instance 25, in every shipping zone where the rules apply. Use the actual fallback instance in each zone and make sure your test address matches the intended zone. The plugin will not create the fallback, so it must already be enabled and available for the destination. Other methods remain unrestricted unless you add them to the restriction map, although WooCommerce or another extension may still affect their availability. These rules do not govern the separate block-based pickup option.

Backup Required
Back up your site files and database before making changes, and build and test the plugin on a staging site before deploying it to production.

You might also like:

Hide Price In WooCommerce: Boost Sales by Requiring Login

Learn how to Hide Price In WooCommerce for guest users with a simple code snippet. Boost your store's leads and...

Read more →

Identify shipping method instances

In the WordPress dashboard, go to WooCommerce > Settings > Shipping and open the zone that matches your test address. Review its enabled shipping methods, including the unrestricted fallback. A method ID identifies the type of method, such as flat_rate; an instance ID identifies one configured occurrence of that method in a zone. Two flat rate rows can therefore share a method ID but have different instance IDs.

Open each method’s settings and look for an instance identifier in the configuration URL, such as instance_id=12, if your WooCommerce interface exposes it. Alternatively, use a PHP debugger when a test package is calculated and inspect the rate IDs passed to the woocommerce_package_rates filter. A rate such as flat_rate:12 identifies the method and instance together. Record the IDs for both restricted methods and the separate fallback, then substitute the actual method-instance pairs in the implementation. Do not copy the example IDs blindly: your store and its zones will have their own instances.

WooCommerce Shipping By Weight - Shipping Zone Rules
Shipping Zone Rules

Step 2: Implement WooCommerce Shipping By Weight

With the method instances recorded, build a site-specific plugin that hooks into the WooCommerce package-rate filter. WooCommerce passes the available rates and the current package to the filter separately for each shipping package. This matters when another extension splits a cart into multiple shipments: each package is assessed on its own, rather than against a combined order weight. The filter changes which existing rates are offered; it does not create shipping methods or change their prices.

The plugin will calculate each package total from shippable product weights and quantities, converting the configured store weight unit to kilograms before applying the limits. It will match both the method ID and instance ID, so other instances of the same method remain untouched. A package at a limit remains eligible; only a total above that limit removes its restricted rate. If a reliable weight cannot be established, the configured restricted rates are removed conservatively. An unrestricted fallback must already be enabled for the matching zone; the code cannot guarantee its availability if WooCommerce or another extension excludes it.

Create the plugin and register the filter

On your staging site, create wp-content/plugins/pnet-weight-shipping/pnet-weight-shipping.php and paste in the complete plugin below. Replace the example instance IDs in the limits map with the IDs you recorded for your store, then activate the plugin in Plugins. The map pairs each method ID with its instance ID, so another instance of the same method is not restricted accidentally.

The helper returns null when it cannot establish a reliable package weight. The filter then removes the mapped rates for that package; otherwise, it removes a rate only when the total is strictly greater than its limit. A package at exactly 10 kg or 20 kg remains eligible for the corresponding method. The separate fallback is not added by this code and must already be available for the destination. The WordPress add_filter reference explains the hook registration; here, the final argument makes both rates and package data available to the callback.

PHP
<?php
/**
 * Plugin Name: PixelNet Weight Shipping Restrictions
 * Description: Restricts selected shipping rate instances by package weight.
 * Version: 1.0.0
 * Requires PHP: 8.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Calculate a package weight in kilograms, or return null if unknown.
 *
 * @param mixed $package WooCommerce shipping package.
 * @return float|null
 */
function pnet_package_weight_kg( $package ) {
    if (
        ! is_array( $package ) ||
        ! isset( $package&#91;'contents'&#93; ) ||
        ! is_array( $package&#91;'contents'&#93; ) ||
        empty( $package&#91;'contents'&#93; ) ||
        ! function_exists( 'wc_get_weight' )
    ) {
        return null;
    }

    $unit = get_option( 'woocommerce_weight_unit', 'kg' );
    if ( ! in_array( $unit, array( 'kg', 'g', 'lbs', 'oz' ), true ) ) {
        return null;
    }

    $total = 0.0;
    $has_shippable_item = false;

    foreach ( $package&#91;'contents'&#93; as $item ) {
        if (
            ! is_array( $item ) ||
            ! isset( $item&#91;'data'&#93;, $item&#91;'quantity'&#93; ) ||
            ! ( $item&#91;'data'&#93; instanceof WC_Product ) ||
            ! is_numeric( $item&#91;'quantity'&#93; )
        ) {
            return null;
        }

        $quantity = (float) $item&#91;'quantity'&#93;;
        if ( ! is_finite( $quantity ) || $quantity <= 0 ) {
            return null;
        }

        $product = $item&#91;'data'&#93;;
        if ( ! $product->needs_shipping() ) {
            continue;
        }

        $has_shippable_item = true;
        $weight = $product->get_weight();
        if ( ! is_numeric( $weight ) ) {
            return null;
        }

        $weight = (float) $weight;
        if ( ! is_finite( $weight ) || $weight <= 0 ) {
            return null;
        }

        $weight_kg = wc_get_weight( $weight, 'kg', $unit );
        if ( ! is_numeric( $weight_kg ) ) {
            return null;
        }

        $weight_kg = (float) $weight_kg;
        if ( ! is_finite( $weight_kg ) || $weight_kg <= 0 ) {
            return null;
        }

        $total += $weight_kg * $quantity;
        if ( ! is_finite( $total ) || $total <= 0 ) {
            return null;
        }
    }

    return $has_shippable_item ? $total : null;
}

/**
 * Remove mapped rates when a package exceeds their limits or is unknown.
 *
 * @param array $rates Available shipping rates.
 * @param array $package WooCommerce shipping package.
 * @return array
 */
function pnet_filter_weight_shipping_rates( $rates, $package ) {
    // Replace these example method-instance pairs with your own IDs.
    $limits = array(
        'flat_rate:12'    => 10.0,
        'local_pickup:15' => 20.0,
    );

    $weight_kg = pnet_package_weight_kg( $package );

    foreach ( $rates as $key => $rate ) {
        if ( ! ( $rate instanceof WC_Shipping_Rate ) ) {
            continue;
        }

        $identifier = $rate->get_method_id() . ':' . $rate->get_instance_id();
        if (
            array_key_exists( $identifier, $limits ) &&
            ( null === $weight_kg || $weight_kg > $limits[ $identifier ] )
        ) {
            unset( $rates[ $key ] );
        }
    }

    return $rates;
}

add_filter( 'woocommerce_package_rates', 'pnet_filter_weight_shipping_rates', 10, 2 );

Understand the package calculation

For WooCommerce Shipping By Weight, the helper calculates a total from the items in the current package. Suppose your store uses grams and the package contains two units of a 1,500 g product and three units of a 500 g product. The helper converts each unit weight to kilograms before multiplying by its package quantity: 1.5 kg × 2 gives 3 kg, and 0.5 kg × 3 gives 1.5 kg. The package total is therefore 4.5 kg, so both example restricted methods remain eligible.

The product object provides its effective weight through get_weight(), including the effective weight of a variation. Products that do not need shipping, such as virtual products, do not contribute to the total. The calculation uses the quantities in the package, not necessarily the quantities for the entire order. If an extension splits an order into shipments, each package is evaluated independently against the limits.

If the package data is malformed, a shippable item has a missing or invalid weight, or no shippable item can be identified, the helper returns an unknown weight. The filter then removes both configured restricted rates rather than assuming a zero total. An unrestricted fallback or another unlisted rate can still appear, but it must already be available for the destination; another extension may also affect it.

Step 3: Test the shipping boundaries

On your staging site, enter a delivery address that matches the shipping zone containing your configured restricted methods and unrestricted fallback. Add a physical product with a known, positive weight, and confirm the store weight unit before comparing results. The test should exercise the actual method instances in your plugin, not the illustrative IDs unless those happen to match your store. For WooCommerce Shipping By Weight, inspect the rates returned for each package rather than assuming the combined cart weight determines every shipment.

Work through the limits from both sides: include a package exactly at each maximum and another just above it. The corresponding restricted method should remain eligible at the maximum and disappear only above it; an unknown package weight should remove both configured restricted rates. Check that the separate fallback remains available for the address, while remembering that the plugin does not create it or prevent another extension from removing it. Recalculate shipping after changing the cart, and record the package weight, destination, and displayed methods for each case. If the results differ from your policy, resolve the mismatch on staging before deploying.

Run boundary and missing-weight tests

With the store weight unit set to kilograms, build packages at the following totals. The table assumes the two example restricted methods and a separately configured fallback are available for the test address.

Package weight Flat rate Local pickup Fallback
2 kg Available Available Available
10 kg Available Available Available
10.001 kg Unavailable Available Available
20 kg Unavailable Available Available
20.001 kg Unavailable Unavailable Available
WooCommerce Shipping By Weight - Checkout Boundary Tests
Checkout Boundary Tests

Next, test a shippable product with an empty weight, then with a zero weight. Both restricted methods should disappear in each case; the fallback should remain available.

Test multiple quantities and a variation with a known effective weight. Add a virtual item alongside a physical product and confirm it does not change the package total. Repeat a boundary test in another store unit, such as 10,000 g, and, if available, test split packages independently.

Verify the result in cart and checkout

Using the matching test address, repeat a few of the previous weight tests through the customer journey. After each cart change, update the cart and recalculate shipping using the controls available in your store. Compare the offered methods in the cart with those shown at checkout for the same address and package contents. If the cart displays only an estimate, confirm the full selection at checkout.

Select a restricted method, then change the cart so that method is no longer eligible. Return to checkout and confirm it is no longer offered or retained as the selected shipping rate. Select the fallback if needed, and verify that checkout can proceed with it. Where an extension splits shipments, check the options for each package rather than comparing only the combined cart weight.

Test the classic and block-based checkout experiences if your store uses them. The configured local_pickup instance is a shipping-zone method; a separate block-based pickup option is not controlled by this filter and may still appear. Use a test payment gateway for any order you place, and review the submitted order to confirm the intended shipping method was recorded.

You might also like:

How to Easily Add a WooCommerce New Product Badge Programmatically

Boost your store's click-through rates by learning how to add a WooCommerce new product badge programmatically. A simple, copy-paste guide...

Read more →

Step 4: Deploy and maintain the rules

Back up the production site, then deploy the tested plugin to wp-content/plugins/pnet-weight-shipping/. Before activating it, replace the example or staging IDs in the limits map with the actual production method-instance pairs. Instance IDs can differ between environments, even when method names look identical. Keep the unrestricted fallback out of the map and confirm it is enabled for each applicable production zone. Activate the plugin in Plugins, then use a matching address and known product weights for a small checkout smoke test. Check a package below and just above each configured limit, plus a product with an unknown weight. Confirm that the expected restricted methods disappear and the fallback remains available. If you place an order, use an approved test payment method and clean up the test order afterward.

Record the affected zones, restricted method and instance IDs, limits in kilograms, and fallback methods in your deployment notes. Include the plugin version, where its configuration is maintained, and who is responsible for future changes. Retest after updating product weights, shipping zones, methods, or extensions, and keep a copy of the last tested plugin release for a controlled rollback.

Refresh cached rates during testing

WooCommerce can reuse shipping rates stored in the customer session, so a checkout page may show an earlier result after you change the plugin or a product weight. Recalculate shipping in the cart after each test, but do not assume that a page refresh alone forces a new rate calculation. If the result looks unchanged, start a fresh customer session in a private browser window, add the test product again, and enter the same destination.

On staging, you can also temporarily enable shipping debug mode under WooCommerce > Settings > Shipping > Shipping options. Save the setting, then recalculate shipping and repeat the case that appeared stale. Debug mode bypasses the shipping-rate cache and can display the matched zone, helping you distinguish a cached result from a configuration issue. Compare the newly calculated methods with the expected outcome before changing the plugin.

Pro Tip
Disable shipping debug mode when testing is complete, and avoid exposing its diagnostic information to customers on production. After disabling it, run one final check in a fresh session to confirm the expected methods still appear during normal operation.

Review zone and plugin interactions

Test the fallback with representative addresses in every zone where the restrictions apply, including the default zone for locations not covered by other zones if your store serves those destinations. WooCommerce uses the first matching zone, so check zone order and destination rules when an address receives unexpected methods. Confirm that the fallback is enabled and actually appears for each test package; configuring it in a zone does not guarantee that another extension will leave it available.

The plugin restricts only the method and instance pairs listed in its limits map. Other instances of the same method type, and rates supplied by third-party extensions, remain unrestricted by this code. If your policy covers another instance, add its actual method ID and instance ID to the map with its limit in kilograms. Keep fallback instances out of the map, and verify their IDs separately in each zone.

Shipping extensions can add, replace, or remove rates before or after this filter runs. If a fallback disappears or a restricted rate returns unexpectedly, inspect the package rates with a debugger at the relevant filter priorities and review the other extension’s settings. Also test any separate block-based pickup option: it is not controlled by the mapped shipping-zone method.

You might also like:

Boost Profits: How to Set a WooCommerce Minimum Order Amount Easily

Learn how to set a WooCommerce minimum order amount without heavy plugins. Increase your store's profitability with this simple, copy-paste...

Read more →

Common Errors

If checkout does not show the expected methods, start with the affected package and destination. These checks can help narrow down the cause before you change the plugin.

  • A restricted method still appears: Confirm that the plugin is active and the address matches the intended zone. Compare the rate’s method ID and instance ID with the limits map, then verify the weight of that specific package. Recalculate shipping in a fresh session.
  • Both restricted methods disappear unexpectedly: Check each shippable product or variation for a positive numeric effective weight. Verify quantities and the configured store weight unit. If those look correct, inspect the package contents with a debugger for malformed item data; the helper treats an unreliable package weight as unknown.
  • No shipping method appears: Enable a separate, unrestricted fallback in the zone matched by the destination. Confirm it is available for the test package and check whether another shipping extension removes or replaces it.
  • A threshold gives the wrong result: Check quantity multiplication, conversion to kilograms, and whether the order is split into packages. The comparison is strictly greater than the limit, so a package exactly at its configured maximum remains eligible for that rate.
  • Changes seem ignored: Start a fresh customer session or temporarily enable shipping debug mode on staging and recalculate. Disable debug mode after testing, then verify the result again under normal conditions.

Conclusion

Heavy packages do not have to receive the same shipping options as lighter ones. The plugin calculates the weight of each shipping package in kilograms and removes only the mapped method instances when their limits are exceeded or the weight is unknown. Rates at an exact limit remain eligible. The plugin leaves an unlisted fallback untouched, but that method must already be configured and available in the zone matched by the customer address; the plugin does not create it or protect it from other extensions.

Keep product and variation weights accurate, and document the production instance IDs, limits, and fallback for each affected zone. Verify the boundary cases and missing-weight behavior in a fresh customer session, including split packages if your store uses them. After deploying, check both cart and checkout with a representative destination to confirm that customers can select an appropriate rate. Treat WooCommerce Shipping By Weight as an ongoing part of your shipping configuration: retest whenever zones, methods, product weights, or shipping extensions change.

Abhik

🚀 Full Stack WP Dev | ☕ Coffee Enthusiast | 🏍️ Biker | 📈 Trader
Hi, I’m Abhik. I’ve been coding since 2007, a journey that began when I outgrew Blogger and migrated to a robust self-hosted stack. That transition introduced me to WordPress, and I’ve been building professional solutions ever since.

Leave a comment