Lesson 6.3. Shipping and Emails

Goal

Write your own shipping method and your own WooCommerce email.

Key concepts

  • Shipping zones → methods in a zone → rates for the cart package
  • A method: extends WC_Shipping_Method, calculate_shipping( $package ), add_rate()
  • Registration: the woocommerce_shipping_methods filter; zone support — supports => shipping-zones, instance-settings
  • Rates are cached in the session: when the conditions change, the package hash changes
  • Email: extends WC_Email, a template in the plugin, registration through woocommerce_email_classes

Diagram

flowchart LR
  CART["Cart → package<br/>items, address"] --> Z{"Zone by address"}
  Z --> M1["Courier service<br/>calculate_shipping()"]
  Z --> M2["Local pickup"]
  M1 --> R["add_rate()<br/>price, label, meta"]
  M2 --> R
  R --> UI["Choice in cart / checkout"]

Code

A shipping method priced by weight:

PHP
<?php
add_action( 'woocommerce_shipping_init', static function () {
	class My_Weight_Shipping extends WC_Shipping_Method {
		public function __construct( $instance_id = 0 ) {
			$this->id                 = 'my_weight';
			$this->instance_id        = absint( $instance_id );
			$this->method_title       = 'Shipping by weight';
			$this->supports           = [ 'shipping-zones', 'instance-settings' ];
			$this->instance_form_fields = [
				'title'   => [ 'title' => 'Title', 'type' => 'text', 'default' => 'Courier' ],
				'per_kg'  => [ 'title' => 'Price per kg', 'type' => 'number', 'default' => 40 ],
			];
			$this->title = $this->get_option( 'title' );
			add_action( "woocommerce_update_options_shipping_{$this->id}", [ $this, 'process_admin_options' ] );
		}

		public function calculate_shipping( $package = [] ) {
			$weight = 0.0;
			foreach ( $package['contents'] as $item ) {
				$weight += (float) $item['data']->get_weight() * $item['quantity'];
			}
			$this->add_rate( [
				'id'    => $this->get_rate_id(),
				'label' => $this->title,
				'cost'  => max( 1, ceil( $weight ) ) * (float) $this->get_option( 'per_kg' ),
			] );
		}
	}
} );

add_filter( 'woocommerce_shipping_methods', static function ( array $methods ): array {
	$methods['my_weight'] = 'My_Weight_Shipping';
	return $methods;
} );

Common mistakes

SymptomCauseFix
The shipping price doesn't update after a settings changeRates are cached in the sessionClear the shipping cache (WooCommerce → Status → Tools) or change the cart
The method isn't visible in a zoneNo shipping-zones in supportsAdd it and use instance_form_fields
Weight 0 — shipping is freeProducts have no weight filled inA minimum rate and a check of product data

Weak and strong answer

Question: How do you build shipping that depends on weight and city?

Weak answer. Add a field to checkout and calculate the price in JS.

Strong answer. A custom WC_Shipping_Method in the zones you need. calculate_shipping() sums the weight from the package, takes the city from $package['destination'] and adds a rate with add_rate(). The calculation is on the server, so it works in both checkouts and through the Store API. I cache the provider's tariffs.

Why the second is stronger: Server-side calculation through the built-in mechanism, not a workaround on the frontend.

Practice

Write a "Shipping by weight" method with a price-per-kg setting. Add it to the "Ukraine" zone (in the terminal: wp wc shipping_zone_method create). Create your own email "Order sent to ERP" that goes to the administrator.

wp / curl — Module 6. Orders, Payments, Shipping

Interview Questions

An array with the cart items, the shipping address and the total, for which the methods calculate rates. The cart can be split into several packages with woocommerce_cart_shipping_packages.

Rates are cached in the session by the package hash. If only the method settings changed, the cart takes the old cache. Clear the shipping cache in tests.

A class extends WC_Email with trigger() and templates, registered through woocommerce_email_classes. Then the email has its settings in WooCommerce → Settings → Emails.

Save your progress

Sign in or create a free account to mark lessons as completed and continue the whole course. You will come back to this lesson.