Code

Write a custom WooCommerce shipping method

A weight-tiered flat rate shipping method scenario that covers WC_Shipping_Method structure, rate caching invalidation, and Store API compatibility for block checkout.

Works with Claude / GPT480 uses 4

The prompt

code-custom-woocommerce-shipping-method
I need a custom WooCommerce shipping method called "Weight Tier Shipping" that charges:
- $5 flat for carts under 5kg
- $12 for carts 5-20kg
- $25 for carts over 20kg
It should show up as an option shop managers can add per shipping zone, same as
built-in flat rate.

ENVIRONMENT: WooCommerce 9.x, using the new block-based checkout (Store API), not the
legacy shortcode checkout.

Build this like a developer who's shipped shipping methods to production before:
1. Show the full class extending `WC_Shipping_Method`, with `__construct()` setting
   `id`, `method_title`, and instance settings support, plus `init_form_fields()` and
   `init()` following the standard WooCommerce pattern.
2. Implement `calculate_shipping()` using `WC()->cart->get_cart_contents_weight()` to
   pick the tier, and add the rate via `add_rate()` with a proper `cost` and label.
3. Register the method via the `woocommerce_shipping_methods` filter, and explain the
   one step people forget: the class needs to be registered on `woocommerce_shipping_init`
   or via autoload, not just declared, or it silently won't appear in the zone settings.
4. Flag the caching edge case: WooCommerce caches calculated shipping rates in a
   session transient keyed by cart contents hash. If a shop manager changes the
   instance settings (e.g. tier thresholds) after that transient is set, customers can
   see stale rates until the cart changes. Show how to bump
   `WC_Cache_Helper::get_transient_version( 'shipping' )` or trigger a package rate
   recalculation when settings are saved.
5. Confirm Store API compatibility: since block checkout doesn't call the legacy
   shortcode shipping calculator directly, verify the method still surfaces correctly
   through `wc_get_shipping_method_count()` and the `cart` Store API endpoint, since a
   method built only against `$package` assumptions from the old cart page can
   sometimes miscalculate if it's reading global `$woocommerce` state that isn't
   populated the same way in the block checkout request context.

Replace the tiers and pricing logic with your actual shipping rules.

Step 4 is the one that generates support tickets months later: a shop manager tweaks a rate and can’t understand why customers still see the old price for a few minutes. Always wire settings saves to a cache bump, not just the calculation logic itself.