Custom WooCommerce Shipping Methods: A Complete Developer Guide
How to build a custom WooCommerce shipping method: extend WC_Shipping_Method, call add_rate(), and the nine WC_Shipping_Rate constructor parameters. Checked against WooCommerce 11.3.0 source on 15 November 2026.

A custom WooCommerce shipping method is a class that extends WC_Shipping_Method, declares an id and a supports list, and calls $this->add_rate() inside calculate_shipping(). If you build the rate object yourself instead, the WC_Shipping_Rate constructor takes nine arguments in a fixed order: id, label, cost, taxes, method ID, instance ID, tax status, description and delivery time. We checked every class, argument and hook in this guide against the WooCommerce docs and the GitHub source on 15 November 2026 (stable release 11.3.0, trunk at 11.4.0-dev).
Below you get a complete working method with weight and dimensional-weight pricing, a free-shipping threshold and a zone surcharge, then the parts that trip people up: the rate cache, tax handling, and the mistakes that show up again and again in forum threads. The code is syntax-checked on PHP 8.5 and written against the source, but we did not run it in a live store for this refresh. Put it on staging and walk the checkout before you trust it.
WC_Shipping_Rate constructor parameters
WC_Shipping_Rate is the object WooCommerce stores for every rate a customer can pick. Its constructor, as defined in class-wc-shipping-rate.php, takes nine optional arguments in this order. The last two, description and delivery time, are present in the 11.3.0 release and in trunk.
# | Parameter | Type | Default | What it does |
|---|---|---|---|---|
1 |
| string | empty | Unique rate ID, usually |
2 |
| string | empty | Text the customer sees next to the price. |
3 |
| number | 0 | Shipping cost before tax. The docblock says integer, but decimal strings and floats work. |
4 |
| array | empty array | Tax amounts keyed by tax rate ID. Leave empty if you add the rate through |
5 |
| string | empty | ID of the shipping method that produced the rate, for example |
6 |
| int | 0 | The zone instance of that method. 0 for a rate that does not belong to an instance. |
7 |
| string | taxable | Either |
8 |
| string | empty | Short extra text stored on the rate. |
9 |
| string | empty | Delivery estimate stored on the rate. |
Two details from the source save debugging time. First, the setters cast description and delivery time to strings, so pass text, not arrays. Second, add_rate() on the method class does not accept description or delivery_time keys. It creates the WC_Shipping_Rate itself from id, label, cost, taxes, meta data and the method’s own tax status. If you want those two fields filled, build the rate object yourself and add it through the woocommerce_package_rates filter, as shown later in this guide.
How does WooCommerce call a custom shipping method?
WooCommerce does not call your class directly at checkout. It matches the customer’s address to a shipping zone, loads the enabled method instances for that zone, and asks each one for rates. For zone-based methods that is the instance you created when the store owner added your method to the zone.
The sequence, taken from WC_Shipping::calculate_shipping_for_package() and WC_Shipping_Method::get_rates_for_package():
- The cart builds a package: contents, a contents cost, the destination and the user. Most stores have one package.
WC_Shippingfinds the zone that matches the destination and loads its enabled instances.- For each instance,
is_available()runs. Your method is skipped if it returns false. calculate_shipping( $package )runs and callsadd_rate()zero or more times.- The
woocommerce_package_ratesfilter runs on the combined list, and the customer picks one rate.
If your method adds no rate, it simply does not appear. That is the supported way to hide it for destinations or carts you cannot serve. The package array holds contents (cart items with a data product object and a quantity), contents_cost (the line totals of items that need shipping, before tax), destination (country, state, postcode, city and address lines) and the user.
Step 1: register the method
Registration is two hooks. woocommerce_shipping_init is the safe moment to load your class, because WC_Shipping_Method exists by then. The woocommerce_shipping_methods filter adds your class name to the list, keyed by the method ID. The official shipping method API page uses the same pattern. Put this in a plugin, not a theme, so shipping logic survives a theme change.
<?php
/**
* Plugin Name: WCD Dynamic Shipping
* Requires Plugins: woocommerce
*/
defined( 'ABSPATH' ) || exit;
// Load the class only after WooCommerce has defined WC_Shipping_Method.
add_action(
'woocommerce_shipping_init',
static function () {
require_once __DIR__ . '/class-wcd-dynamic-shipping.php';
}
);
// Register it. The array key must match the class's $this->id.
add_filter(
'woocommerce_shipping_methods',
static function ( $methods ) {
$methods['wcd_dynamic'] = 'WCD_Dynamic_Shipping';
return $methods;
}
);The array key must equal the $this->id you set in the class. A mismatch is one of the quieter ways to end up with a method that never appears in a zone.
Step 2: build the method class
This class has five instance settings: the checkout label, a base rate, a rate per kilogram, a dimensional divisor and a free-shipping threshold. It declares shipping-zones, instance-settings and instance-settings-modal, the three values core methods such as flat rate use, so each zone gets its own settings in a modal.
<?php
defined( 'ABSPATH' ) || exit;
class WCD_Dynamic_Shipping extends WC_Shipping_Method {
public function __construct( $instance_id = 0 ) {
$this->id = 'wcd_dynamic';
$this->instance_id = absint( $instance_id );
$this->method_title = __( 'Dynamic weight rate', 'wcd-shipping' );
$this->method_description = __( 'Charges by weight or dimensional weight, with a free-shipping threshold.', 'wcd-shipping' );
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
);
$this->init();
// Without this line the instance settings never save.
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
public function init() {
$this->instance_form_fields = array(
'title' => array(
'title' => __( 'Label at checkout', 'wcd-shipping' ),
'type' => 'text',
'default' => __( 'Shipping', 'wcd-shipping' ),
),
'base_rate' => array(
'title' => __( 'Base rate', 'wcd-shipping' ),
'type' => 'price',
'default' => '5',
),
'rate_per_kg' => array(
'title' => __( 'Rate per kg', 'wcd-shipping' ),
'type' => 'price',
'default' => '1.5',
),
'dim_divisor' => array(
'title' => __( 'Dimensional divisor (cm)', 'wcd-shipping' ),
'type' => 'decimal',
'default' => '5000',
'description' => __( 'Length x width x height divided by this number gives dimensional kg.', 'wcd-shipping' ),
'desc_tip' => true,
),
'free_threshold' => array(
'title' => __( 'Free shipping from', 'wcd-shipping' ),
'type' => 'price',
'default' => '0',
'description' => __( '0 disables free shipping.', 'wcd-shipping' ),
'desc_tip' => true,
),
);
$this->title = $this->get_option( 'title' );
}
public function calculate_shipping( $package = array() ) {
$threshold = (float) $this->get_option( 'free_threshold' );
if ( $threshold > 0 && $package['contents_cost'] >= $threshold ) {
$this->add_rate(
array(
'id' => $this->get_rate_id( 'free' ),
'label' => __( 'Free shipping', 'wcd-shipping' ),
'cost' => 0,
'package' => $package,
)
);
return;
}
$cost = (float) $this->get_option( 'base_rate' );
$cost += $this->get_chargeable_weight( $package ) * (float) $this->get_option( 'rate_per_kg' );
$cost *= $this->get_zone_multiplier( $package['destination'] );
$this->add_rate(
array(
'id' => $this->get_rate_id(),
'label' => $this->title,
'cost' => $cost,
'package' => $package,
)
);
}
/**
* Greater of actual and dimensional weight, in kg, never below 0.1.
*/
private function get_chargeable_weight( array $package ): float {
$actual = 0.0;
$volume = 0.0; // cm3
foreach ( $package['contents'] as $item ) {
$product = $item['data'];
$qty = (int) $item['quantity'];
$actual += (float) wc_get_weight( (float) $product->get_weight(), 'kg' ) * $qty;
$volume += (float) wc_get_dimension( (float) $product->get_length(), 'cm' )
* (float) wc_get_dimension( (float) $product->get_width(), 'cm' )
* (float) wc_get_dimension( (float) $product->get_height(), 'cm' )
* $qty;
}
$divisor = max( 1.0, (float) $this->get_option( 'dim_divisor' ) );
return max( 0.1, $actual, $volume / $divisor );
}
private function get_zone_multiplier( array $destination ): float {
$multiplier = 1.0;
if ( 'US' !== $destination['country'] ) {
$multiplier = 2.0;
} elseif ( in_array( $destination['state'], array( 'AK', 'HI' ), true ) ) {
$multiplier = 1.75;
}
return (float) apply_filters( 'wcd_dynamic_shipping_multiplier', $multiplier, $destination, $this );
}
}Checked against source on 15 November 2026: the constructor signature, the supports values, the woocommerce_update_options_shipping_ hook and get_rate_id() all match WC_Shipping_Flat_Rate and the abstract class on GitHub. The field types text, price and decimal are generated by WC_Settings_API.
Setting | Default | What it controls |
|---|---|---|
Label at checkout | Shipping | The |
Base rate | 5 | Flat amount added to every shipment. |
Rate per kg | 1.5 | Added for each kilogram of chargeable weight. |
Dimensional divisor (cm) | 5000 | Volume in cubic centimetres divided by this gives dimensional kilograms. |
Free shipping from | 0 | Carts with a contents cost at or above this get a free rate. 0 turns it off. |
How the rate is worked out
The method first checks the free-shipping threshold. If the cart qualifies, it adds one rate with a cost of 0 and returns. Otherwise it takes the chargeable weight, multiplies it by the per-kilogram rate, adds the base rate, and applies a destination multiplier. Currency amounts are plain numbers in the store currency. add_rate() formats the final cost with wc_format_decimal().
Dimensional weight
Carriers charge for the space a parcel takes as well as its mass, and they bill whichever figure is higher. Dimensional weight is length times width times height divided by a carrier-specific divisor. A divisor of 5000 with centimetre measurements is a common figure, but carriers publish their own, so take the number from your carrier’s rate guide instead of copying ours.
A 40 x 30 x 20 cm box has a volume of 24,000 cubic centimetres. Divided by 5000 that is 4.8 kg. If the contents weigh 2 kg, you charge for 4.8 kg. The get_chargeable_weight() method does this across the whole package, converts units with wc_get_weight() and wc_get_dimension(), and never returns less than 0.1 kg so a store with missing product weights does not quote a zero rate. It adds all item volumes together, which assumes everything ships in one box. That is the main simplification to replace if you need real box packing.
Destination multipliers
The example charges 1.75 times the normal rate to Alaska and Hawaii and double to any destination outside the US. That is a placeholder. The multiplier passes through the wcd_dynamic_shipping_multiplier filter so a site can change it without editing the class. For real stores, move these numbers into instance settings or a settings page, because shipping rules change more often than code is deployed.
How do you add several rates from one method?
Call add_rate() more than once with different IDs. get_rate_id( 'express' ) returns wcd_dynamic:12:express for instance 12, so each tier keeps a unique, stable ID. That ID is what WooCommerce stores in the session as the chosen method, so keep it stable between releases or customers mid-checkout lose their selection.
$this->add_rate( array(
'id' => $this->get_rate_id( 'standard' ),
'label' => __( 'Standard', 'wcd-shipping' ),
'cost' => $standard_cost,
'package' => $package,
) );
$this->add_rate( array(
'id' => $this->get_rate_id( 'express' ),
'label' => __( 'Express', 'wcd-shipping' ),
'cost' => $standard_cost * 2,
'package' => $package,
) );What add_rate accepts
These are the defaults in WC_Shipping_Method::add_rate() in trunk. Anything you pass is merged over them with wp_parse_args(), then passed through the woocommerce_shipping_method_add_rate_args filter.
Argument | Default | Notes |
|---|---|---|
|
| Required. If empty, |
| empty | Required. An empty label also means no rate is added, with no error. |
| 0 | A number, or an array of costs when you price per item. |
| empty | Pass an array, leave empty to let WooCommerce calculate, or pass |
|
| Use |
| empty array | Key and value pairs stored on the rate and shown in the order. |
| false | Pass the package so the rate meta lists the items it was calculated for. |
| false | Decimal places used when formatting the cost. |
Can you build a rate without add_rate?
Yes. Rates that do not belong to a method class, such as a pickup option you inject for every package, can be added with the woocommerce_package_rates filter. This is also the only route to fill the description and delivery time fields, because add_rate() does not take them. The array is keyed by rate ID.
add_filter(
'woocommerce_package_rates',
static function ( $rates, $package ) {
$rate = new WC_Shipping_Rate(
'wcd_dynamic:pickup', // $id
'Collect from the warehouse', // $label
0, // $cost
array(), // $taxes
'wcd_dynamic', // $method_id
0, // $instance_id
'none', // $tax_status
'Ready within two hours', // $description
'Same day' // $delivery_time
);
$rates[ $rate->get_id() ] = $rate;
return $rates;
},
10,
2
);We used none as the tax status because the rate is free. With a cost of 0 there is nothing to tax anyway, but none states the intent. If you add a paid rate this way, pass the taxes array yourself, since only add_rate() calculates them for you.
Does WooCommerce cache shipping rates?
Yes, and this matters more than any custom cache you write. WooCommerce stores the rates it calculated for each package in the customer session under shipping_for_package_ plus the package index, together with a hash of the package. On the next request it recalculates only if the hash changed or if shipping debug mode is on. The hash is built in a private get_package_hash() method in class-wc-shipping.php. It includes the package contents, the destination and, when taxes are on, the customer’s tax address.
That corrects a common claim, including one in the earlier version of this post: calculate_shipping() is not called on every cart update. It runs when the package changes, which means a new quantity, a new product, a new address or a changed shipping setting. Since WooCommerce 11.0.0 a filter, woocommerce_shipping_package_hash_ignored_fields, lets you exclude fields from the hash. By default subtotal, total, package_id, package_name, rates and package_index are ignored.
Two consequences for your code. If your rate depends on something outside the package, such as a custom checkout field, a delivery date or a user meta value, the hash does not change when that value changes, and the customer keeps the old rate. Add the value to the package through the woocommerce_cart_shipping_packages filter so it becomes part of the hash. And when you are testing, turn on WooCommerce, Settings, Shipping, Shipping options, Debug mode, which forces a recalculation on every request.
When a transient is worth it
The session cache does not help across customers. If calculate_shipping() calls a carrier API, a second customer with the same destination and weight triggers the same remote request. A short transient keyed on the inputs avoids that. Round the weight so near-identical parcels share a key, and cache only successful responses.
$key = 'wcd_rate_' . md5( wp_json_encode( array(
$package['destination']['country'],
$package['destination']['state'],
$package['destination']['postcode'],
round( $weight * 2 ) / 2, // nearest 0.5 kg
) ) );
$quote = get_transient( $key );
if ( false === $quote ) {
$quote = $this->fetch_carrier_quote( $package, $weight ); // your API call, null on failure
if ( null !== $quote ) {
set_transient( $key, $quote, HOUR_IN_SECONDS );
}
}
if ( null === $quote ) {
return; // no rate: the customer sees the other methods in the zone
}Returning without a rate is better than inventing one when the carrier is down, unless your business rule says a fallback flat rate is acceptable. If it is, add it explicitly and log the failure with wc_get_logger() so it shows in WooCommerce, Status, Logs. For the carrier side of this, our guide to multi-carrier rate comparison covers UPS, FedEx, USPS and aggregator APIs in more depth.
How are taxes handled on a custom rate?
If you leave taxes empty, add_rate() calculates shipping tax for you, but only when the cost is above zero and is_taxable() is true. That check needs taxes enabled in the store, the method’s tax_status set to taxable, and a customer who is not VAT exempt. The method’s tax_status property defaults to taxable; the core methods expose it as a setting named Tax status. Add the same field to your form fields if store owners need to turn shipping tax off per zone.
Trunk also has a filter named woocommerce_shipping_prices_include_tax, added in 10.6.0. When it returns true, WooCommerce treats your cost as tax-inclusive and subtracts the calculated tax to get the net figure. It defaults to false. If you sell in markets where customers see tax-inclusive shipping prices, read that part of add_rate() before you choose how to enter costs. Stores that sell in the EU should also see our look at EU VAT plugins.
Common mistakes people report
We went through the WooCommerce source, the WordPress.org support forum and developer Q and A. Some threads are years old, but each cause still matches the current source, and the pattern repeats. These are the problems we saw most, paraphrased, with the source of each. Checked on 15 November 2026.
- Method visible in the dropdown but missing from the zone settings, or the reverse. The usual causes are a missing
shipping-zonesorinstance-settingsentry insupports, or a filter key that does not match$this->id. Mike Jolley’s shipping method gist and the official API page show the working setup, includinginstance-settings-modalfor the settings modal. - Fatal error that
WC_Shipping_Methodis not found. A poster in this 2021 support thread hit it after wrapping the class in a function that ran too early. Load the class onwoocommerce_shipping_init, not at plugin load. - The method shows in the zone but never appears at checkout. In the same thread the method returned no rate at first. The reply was to define
instance_form_fieldsand return a rate withadd_rate(). Remember thatadd_rate()silently drops a rate with an empty id or label. - Cost does not change after the customer edits a custom field. Another forum thread, an old one from 2016, describes a rate that only updated for default address fields. This is most likely the package hash at work, though the poster blamed debug mode: WooCommerce reuses stored rates until the package changes, so add your custom input to the package.
- Settings that do not save. Core methods hook
process_admin_optionstowoocommerce_update_options_shipping_plus the method ID in the constructor, and your class needs the same line. We did not find a fresh forum report of this one, so treat it as a source-based check, not a trend.
A fix that works on one site is not always the cause on yours. Before you change code, add the method to a fresh zone on a staging copy with only WooCommerce active, because another shipping plugin can hide or reorder rates through woocommerce_package_rates.
Should you write a method or use a plugin?
A custom method is the right call when your pricing rule cannot be expressed as a table. It is the wrong call when a table does the job, because every line of shipping code is a line you maintain through each WooCommerce release. This is how we decide.
Situation | Better fit | Why |
|---|---|---|
Flat price per zone, free above a threshold | Core flat rate and free shipping | No code, already tested by thousands of stores. |
Price by weight bands, quantity or cart total | A table rate plugin | Store owners can edit the table themselves. |
Live carrier quotes and labels | A carrier plugin or an aggregator API | The vendor keeps up with carrier API changes. |
Pricing from your own data: dimensional weight, supplier zones, contract rates | A custom method | The rule lives in code and can read your own tables. |
Different rules per vendor | A custom method plus marketplace hooks | See our vendor shipping rules guide. |
We are a WooCommerce development team, so we do build custom methods for stores whose contract rates or packaging rules no plugin covers. We would rather tell you when a flat rate or a table rate plugin is enough, because it costs you less and breaks less. Compare the plugin route first, then decide.
How do you test a custom shipping method?
Test the cart shapes that break shipping code, not just a single happy path. Use a staging site, switch on shipping debug mode, and work through this list.
- A product with no weight or dimensions. The method should return a rate, not a zero or a PHP warning.
- A cart that mixes physical and virtual items. Virtual items are not part of the package contents, so only the physical ones should be priced.
- The free-shipping boundary at exactly the threshold, one cent below and one cent above.
- A destination that triggers the multiplier, and one that does not.
- The method added to two zones with different settings, to confirm each instance reads its own values.
- A change of address, then a change of quantity, to confirm the rate refreshes. Do this once with debug mode off.
- A tax-enabled store, to confirm the shipping tax line matches your expectation.
- If you call a carrier API, an invalid key or a timeout, to confirm checkout still works.
Enable WP_DEBUG and WP_DEBUG_LOG while you do this. PHP 8.1 and 8.2 added deprecations (null passed to string functions, dynamic properties) that older tutorials still trigger, and shipping code runs on every checkout. If you work on payment methods too, the same loading rules apply to gateways, which we cover in building custom payment gateways.
Frequently asked questions
How many arguments does the WC_Shipping_Rate constructor take?
Nine, all optional: id, label, cost, taxes, method ID, instance ID, tax status, description and delivery time. The defaults are empty strings, 0, an empty array, an empty string, 0, taxable, and two empty strings. The class is in includes/class-wc-shipping-rate.php in the WooCommerce repository.
Can I pass description and delivery_time to add_rate?
Not in the trunk source we read. The keys are merged into the argument array, but add_rate() only reads id, label, cost, taxes, calc_tax, meta_data, package and price_decimals when it creates the rate. To fill those two fields, construct WC_Shipping_Rate yourself and add it with woocommerce_package_rates.
Why does my shipping method not appear at checkout?
Work down this list: the class loads on woocommerce_shipping_init; the filter key equals the class $this->id; supports includes shipping-zones and instance-settings; the method is added to a zone that matches the test address; the instance is enabled; and calculate_shipping() really calls add_rate() with a non-empty id and label.
Do I need to extend WC_Shipping_Method?
For a method that shows in zones and has settings, yes. The abstract class provides add_rate(), get_rate_id(), instance settings storage and process_admin_options(). To add or edit rates from other methods you only need the woocommerce_package_rates filter.
Does this work with the Checkout block?
The rates themselves come from the same shipping classes, so a method registered this way is offered in both the classic and block checkout. Code that prints extra markup through classic template hooks is a different matter and should be checked in the block checkout on your own site. Our guide to migrating to checkout blocks lists what to re-test.
Where do I find the current source?
The three files to read are class-wc-shipping-rate.php, abstract-wc-shipping-method.php and class-wc-shipping.php. Read them at the tag that matches your store, because trunk moves ahead of the stable release.
Where to go next
From here the usual next steps are per-product rate overrides stored as product meta, real box packing for mixed carts, and an admin page that simulates a rate for a destination and weight without placing an order. For developers working through the wider store stack, our WooCommerce developer guide to hooks, architecture and the REST API is the best companion to this one.
If your shipping rules are more than a table can hold and you want a second pair of eyes on the design, talk to our team at WooCustomDev. We start with the simplest option that works and say so when that option is a plugin.
Plugins we build and run
We maintain these ourselves, which is why we can support them on your site.
- BuddyNextThe self-hosted community engine for WordPress
- BuddyXFree community theme, Pro when you outgrow it
- ReignPremium community theme. Add pieces, build anything
- JetonomyCommunity forum and Q&A for WordPress
- EventonomyEvents and RSVPs for WordPress communities
- LearnomyCourses and learning communities on WordPress
- ListoraDirectories and listings your members can browse
- SnipShareCode sharing built for developer communities
- WB Ad ManagerAd placements that turn traffic into revenue
- WP Career BoardA job board your community actually uses
- WP Sell ServicesSell services with offers, orders, and payouts
- MediaVersePhotos, video, and media albums for members
- WB GamificationPoints, badges, and rewards that keep members active
- Product RoadmapPublic roadmaps with voting your users trust
- KanbanomyProject management with a client portal, on your own WordPress site



