Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Payments and Shipping

Custom Shipping Methods

Build a custom WooCommerce shipping method: WC_Shipping_Method, zones, instance settings, calculate_shipping, weight and distance rates, classes and free thresholds.

When a shopper enters an address, WooCommerce asks every shipping method in the matching zone for a price. A shipping method is a PHP class that receives the package (the items going to one destination) and answers with zero or more rates. Flat rate, free shipping and local pickup are all methods built this way. When you need a rule the built-in ones cannot express, such as price by weight bands, by distance to a depot or by carrier tables, you write your own.

This lesson covers the structure of WC_Shipping_Method, how zones and instances fit together, how calculate_shipping() adds rates, how taxes and shipping classes interact, and then practices the pricing logic in runnable plain PHP. The class itself needs WordPress, so it is read-only. For the business side of shipping prices, see Shipping Rates. The cart that produces the package is explained in The Cart and Session.

Zones, methods and instances

flowchart TD
    A["Package destination"] --> B["Find first matching zone"]
    B --> C["Methods added to that zone"]
    C --> D["Flat rate (instance 12)"]
    C --> E["Acme weight rate (instance 13)"]
    E --> F["calculate_shipping()"]
    F --> G["add_rate()"]
    D --> H["Rates shown at checkout"]
    G --> H

A zone picks the methods; each method instance calculates its own rates with its own settings.

A shipping zone is a named region (countries, states or postcode patterns). WooCommerce walks the zones in order and uses the first one that matches the destination; "Locations not covered by your other zones" is the fallback. You add methods to a zone in the admin. Adding the same method type twice creates two instances, each with an instance_id and its own settings. That is why a well-behaved method keeps its configuration in instance settings (per zone) rather than global settings.

The method class

This skeleton is read-only. It declares the method, enables zone support and adds instance settings:

PHP
<?php
class Acme_Weight_Shipping extends WC_Shipping_Method {

    public function __construct( $instance_id = 0 ) {
        $this->id                 = 'acme_weight';
        $this->instance_id        = absint( $instance_id );
        $this->method_title       = __( 'Acme weight rate', 'acme' );
        $this->method_description = __( 'Price by total weight.', 'acme' );
        $this->supports           = [ 'shipping-zones', 'instance-settings', 'instance-settings-modal' ];

        $this->init();
    }

    private function init(): void {
        $this->instance_form_fields = [
            'title' => [
                'title'   => __( 'Label', 'acme' ),
                'type'    => 'text',
                'default' => __( 'Weight based shipping', 'acme' ),
            ],
            'base_cost' => [
                'title'   => __( 'Base cost', 'acme' ),
                'type'    => 'price',
                'default' => '4.00',
            ],
            'per_kg' => [
                'title'   => __( 'Cost per kg', 'acme' ),
                'type'    => 'price',
                'default' => '1.50',
            ],
            'free_over' => [
                'title'       => __( 'Free above subtotal', 'acme' ),
                'type'        => 'price',
                'description' => __( 'Leave empty to disable.', 'acme' ),
                'default'     => '',
            ],
        ];

        $this->title = $this->get_option( 'title' );

        add_action( 'woocommerce_update_options_shipping_' . $this->id, [ $this, 'process_admin_options' ] );
    }

    public function calculate_shipping( $package = [] ): void {
        $weight_kg = 0.0;
        foreach ( $package['contents'] as $item ) {
            $product    = $item['data'];
            $weight_kg += (float) wc_get_weight( (float) $product->get_weight(), 'kg' ) * $item['quantity'];
        }

        $free_over = $this->get_option( 'free_over' );
        if ( '' !== $free_over && $package['contents_cost'] >= (float) $free_over ) {
            $cost = 0.0;
        } else {
            $cost = (float) $this->get_option( 'base_cost' ) + $weight_kg * (float) $this->get_option( 'per_kg' );
        }

        $this->add_rate( [
            'id'    => $this->get_rate_id(),
            'label' => $this->title,
            'cost'  => $cost,
        ] );
    }
}

add_filter( 'woocommerce_shipping_methods', function ( array $methods ): array {
    $methods['acme_weight'] = 'Acme_Weight_Shipping';
    return $methods;
} );

The important details:

  • $supports lists shipping-zones and instance-settings. Without them the method will not appear in the zone screen. The instance-settings-modal entry lets the admin edit settings in a popup.
  • The instance form fields use the same array format as other settings; you read them with get_option(), which is instance-aware for methods that use instance settings.
  • calculate_shipping() does not return anything. It calls add_rate() once per rate you want to offer. Calling it several times offers several choices (for example "Standard" and "Express").
  • A rate array holds id, label and cost. get_rate_id() builds the id from the method id and the instance id, which keeps two instances from colliding. meta_data can carry extra information for the order.
  • Register the class with the woocommerce_shipping_methods filter. As for gateways, load the class after WooCommerce, from plugins_loaded (see Your First WooCommerce Extension).

The package and what you can read from it

The $package array contains the cart items for one shipment. The keys you will use most:

Key Meaning
contents Items; each has data (the product), quantity, line_total and more
contents_cost Total of items that need shipping (before tax, after discounts in most setups)
applied_coupons Coupon codes in use
destination country, state, postcode, city, address
cart_subtotal The cart subtotal for the package

Virtual products and downloads are excluded from the package automatically, so you do not need to filter them out. Products can also be given a shipping class (a taxonomy such as "Bulky" or "Fragile"). Read it with $product->get_shipping_class() (the slug) or get_shipping_class_id(). The built-in flat rate offers per-class costs; in your own method you decide what a class means, such as a surcharge per bulky item.

Taxes on shipping

By default a rate is taxable: add_rate() uses 'taxes' => 'calculated' and WooCommerce works out the tax on the shipping cost with the tax class rules from Taxes, Currency and Formatting. If your cost already includes tax, or the carrier charges no tax, you can pass 'taxes' => false. Whether the displayed shipping price includes tax follows the shop's price display settings. As with product prices, calculate in a consistent unit and round once; use integer minor units in your own helpers as taught in Representing Money Correctly.

Testing and the rate cache

Shipping rates are expensive when they call a carrier API, so WooCommerce stores the calculated rates in the session, keyed by a hash of the package and its settings. While developing you may think your change did nothing when you are looking at a cached result. Turn on Debug mode in WooCommerce > Settings > Shipping > Shipping options to disable that cache, or change the cart contents. If your method calls an external carrier API, add your own short-lived transient so the same address is not priced on every refresh, and fail soft: when the API is down, add no rate (or a clearly labeled fallback) instead of letting checkout crash.

A rate calculator you can run

The stand-in below prices a package in integer cents. It is not WooCommerce: there is no zone matching, no add_rate() and no tax engine. It shows the decisions a method makes: weight bands, a surcharge for a bulky class, a free-shipping threshold, and what happens when nothing applies.

PHP Weight bands, class surcharge and free threshold

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Returning no rate for an overweight package is a deliberate choice: if no method in the zone offers a rate, WooCommerce tells the shopper there are no shipping options, so decide which method handles the odd cases.

Distance-based rates

Distance pricing needs a distance. Real stores usually compute it with a mapping or carrier API from the destination address, or approximate it by postcode prefix. Never call a slow API on every cart refresh without caching, and never put API keys in front-end code. The stand-in below uses a small table of postcode prefixes as a pretend "zone distance", then adds tax the way a store with tax-exclusive prices would show it.

PHP Postcode zones, distance bands and tax on shipping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that '11-200' has a dash, so the prefix is 11 as well: always normalize postcodes before matching. Real postcode rules differ per country, so prefer the zone postcode patterns that WooCommerce already supports when a simple range is enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a shipping method offer a price to the shopper?

    calculate_shipping() returns nothing. Each call to add_rate() registers one selectable rate for the package.
  2. 2. Why should a zone-aware method keep its settings as instance settings?

    Each time an admin adds the method to a zone, a new instance with its own instance_id is created, so per-zone configuration belongs to the instance.
  3. 3. Your new rate does not change while you test. What is a likely reason?

    WooCommerce caches calculated rates per package in the session. Debug mode in the shipping options disables that cache while developing.
  4. 4. What is a sensible behavior when your carrier API is down?

    A failing external service should degrade gracefully. An accidental free rate loses money, and an exception can break the whole checkout page.

Summary

  • A shipping method extends WC_Shipping_Method, declares shipping-zones and instance-settings support and is registered with woocommerce_shipping_methods.
  • calculate_shipping( $package ) reads contents, contents_cost and destination, then calls add_rate() for each choice.
  • Keep per-zone configuration in instance settings and read it with get_option().
  • Rates are taxable by default; pass 'taxes' => false only when that is correct.
  • Rates are cached in the session while shoppers browse, so use shipping debug mode when testing, and cache or fail soft around external APIs.
  • Compute in integer cents, normalize postcodes and decide explicitly what happens when no rule matches.

Next: Custom Transactional Emails