Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Real-World Projects

Project: Delivery Date Slots

Build a WooCommerce delivery slot extension: capacity per slot, classic and block checkout fields, validation, order meta, admin column and email display, with a runnable engine.

Local shops, bakeries, florists and grocers all ask for the same feature: let the customer choose a delivery day and a time window at checkout, and stop selling a window once it is full. It sounds small, and it touches almost everything you learned in this track: a checkout field in both the classic and block checkout, server-side validation, order meta, an admin list column, and email output. It also adds a problem that most extensions never meet, which is capacity: two customers may try to take the last slot at the same moment.

The WooCommerce parts are read-only here. The slot rules (which days are offered, which windows are full, how a booking is reserved and released) are written as a standalone engine in PHP with SQLite so you can run and test them. Prerequisites: Classic Checkout Fields and Validation, Cart and Checkout Blocks Extensibility and Orders and High-Performance Order Storage.

Requirements and design

  • The shop defines windows (for example 09:00-12:00 and 14:00-18:00) with a capacity per window (say 8 orders), a cutoff (orders placed after 15:00 cannot choose tomorrow), a lead time, and closed days (Sundays, holidays).
  • The customer picks one slot at checkout. The server re-checks it on submit, because the list in the browser may be stale.
  • A confirmed slot is stored on the order, shown in the admin list, and printed in the emails.
  • Cancelling or failing an order releases its slot.
flowchart TD
    A["Checkout page<br/>lists open slots"] --> B["Customer submits"]
    B --> C{"Slot still open<br/>and allowed?"}
    C -- no --> D["Validation error,<br/>pick another slot"]
    C -- yes --> E["Reserve slot<br/>(inside a transaction)"]
    E --> F["Save slot on order meta"]
    F --> G["Show in admin and emails"]
    F --> H["Order cancelled or failed:<br/>release slot"]

The decision is made on the server at submit time; the browser list is only a convenience.

Where to keep the data

Two tables of facts exist: the configuration (windows, capacity, closed days) and the bookings. For a small shop, windows and closed days can live in one option array. Bookings, however, should not be computed by counting orders with a meta query on every checkout page view, because meta queries on orders are slow and cannot be made atomic. A small custom table with a unique key per order is better (created with dbDelta() as in Project: Loyalty Points), and the slot is also written to order meta so that the order stays readable without the table.

PHP
<?php
global $wpdb;
$table = $wpdb->prefix . 'acme_slot_bookings';

$sql = "CREATE TABLE {$table} (
    order_id BIGINT UNSIGNED NOT NULL,
    slot_date DATE NOT NULL,
    window_key VARCHAR(20) NOT NULL,
    created_at DATETIME NOT NULL,
    PRIMARY KEY  (order_id),
    KEY slot (slot_date, window_key)
) {$wpdb->get_charset_collate()};";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );

The primary key on order_id means one booking per order, and the index on (slot_date, window_key) makes "how many bookings in this slot?" a cheap query.

The slot engine (runnable)

Study this engine before the WooCommerce glue. It answers three questions: which slots can be offered now, can this slot be booked, and what happens when an order is cancelled.

PHP Delivery slot capacity engine

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.

Read the output with the rules in mind: the second customer for the single 14-18 seat is refused with full; Sunday and the closed date are rejected by isDateAllowed; and after the 15:00 cutoff Saturday disappears (the earliest date moves one day later, and the closed Sunday and Monday push the first offer to Tuesday the 5th). In production the book() step needs real atomicity: use a transaction and either SELECT ... FOR UPDATE on the slot row or a counter row per slot that you increment with a conditional UPDATE ... WHERE used < capacity. Counting and inserting in two steps without a lock can oversell under heavy concurrency, so test it.

Step 1: the classic checkout field

For the shortcode checkout, add the field with the checkout fields filter. A select of open slots works well, and the options come from the same engine:

PHP
<?php
add_filter( 'woocommerce_checkout_fields', function ( array $fields ): array {
    $options = [ '' => __( 'Choose a delivery slot', 'acme-slots' ) ];
    foreach ( Acme_Slots::offer( new DateTimeImmutable( 'now', wp_timezone() ) ) as $date => $windows ) {
        foreach ( $windows as $key => $left ) {
            $options[ $date . '|' . $key ] = sprintf( '%s, %s', wp_date( 'D j M', strtotime( $date ) ), $key );
        }
    }
    $fields['order']['acme_delivery_slot'] = [
        'type'     => 'select',
        'label'    => __( 'Delivery slot', 'acme-slots' ),
        'required' => true,
        'options'  => $options,
        'priority' => 95,
    ];
    return $fields;
} );

Use the store's timezone (wp_timezone()), not the server's, when deciding what "tomorrow" or "after 15:00" means. Only offer the field when the cart needs shipping to a country you serve, which you can check with WC()->cart->needs_shipping().

Remember the checkout page can be cached by a plugin or CDN; a slot list that changes as capacity fills must not be cached for everyone. WooCommerce excludes cart and checkout pages from page caching by convention, but verify it for your host.

Step 2: validation and saving

Validate on submit with the server-side engine. The posted value is a plain string from the browser and is treated that way:

PHP
<?php
add_action( 'woocommerce_after_checkout_validation', function ( array $data, WP_Error $errors ) {
    $raw = isset( $_POST['acme_delivery_slot'] ) ? wc_clean( wp_unslash( $_POST['acme_delivery_slot'] ) ) : '';
    [ $date, $window ] = array_pad( explode( '|', (string) $raw, 2 ), 2, '' );

    if ( ! Acme_Slots::is_open( $date, $window, new DateTimeImmutable( 'now', wp_timezone() ) ) ) {
        $errors->add( 'acme_slot', __( 'That delivery slot is no longer available. Please choose another.', 'acme-slots' ) );
    }
}, 10, 2 );

add_action( 'woocommerce_checkout_create_order', function ( WC_Order $order, array $data ) {
    $raw = isset( $_POST['acme_delivery_slot'] ) ? wc_clean( wp_unslash( $_POST['acme_delivery_slot'] ) ) : '';
    [ $date, $window ] = array_pad( explode( '|', (string) $raw, 2 ), 2, '' );
    $order->update_meta_data( '_acme_delivery_date', $date );
    $order->update_meta_data( '_acme_delivery_window', $window );
}, 10, 2 );

add_action( 'woocommerce_checkout_order_processed', function ( int $order_id ) {
    $order = wc_get_order( $order_id );
    $ok = Acme_Slots::book( $order_id, $order->get_meta( '_acme_delivery_date' ), $order->get_meta( '_acme_delivery_window' ) );
    if ( 'booked' !== $ok ) {
        $order->update_status( 'on-hold', 'Delivery slot could not be reserved: ' . $ok );
    }
}, 10, 1 );

Validation is a courtesy to the shopper; the reservation is what protects capacity. Two shoppers can both pass validation for the last seat, so the reservation must be able to fail, and your code needs a fallback for that moment (here: put the order on hold with a note, so the owner contacts the customer). Better still, reserve inside the same request in an earlier hook and return a validation error if the reservation fails.

Step 3: the block checkout

The block checkout does not run woocommerce_checkout_fields. It has its own server-side mechanism for extra fields, the additional checkout fields API, where you register a field in PHP and WooCommerce renders, validates and stores it:

PHP
<?php
add_action( 'woocommerce_init', function () {
    woocommerce_register_additional_checkout_field( [
        'id'       => 'acme/delivery-slot',
        'label'    => __( 'Delivery slot', 'acme-slots' ),
        'location' => 'order',
        'type'     => 'select',
        'required' => true,
        'options'  => Acme_Slots::select_options(),
    ] );
} );

Key differences from the classic checkout: the option list is built when WooCommerce initialises, so a list that changes minute by minute is awkward (you validate on submit and show an error), and the stored value lives in a different place than your classic meta key. A common approach is to read both sources in one helper (Acme_Slots::slot_for_order( $order )). Check the current WooCommerce documentation for the exact field options and meta keys of your minimum supported version, and declare block compatibility only when you tested it. The details of block extensibility are in Cart and Checkout Blocks Extensibility.

Step 4: admin column and email

For the orders list under HPOS, the column hooks differ from the legacy post list; register both:

PHP
<?php
// HPOS orders screen
add_filter( 'manage_woocommerce_page_wc-orders_columns', 'acme_slot_column' );
add_action( 'manage_woocommerce_page_wc-orders_custom_column', 'acme_slot_column_value', 10, 2 );
// Legacy posts screen
add_filter( 'manage_edit-shop_order_columns', 'acme_slot_column' );
add_action( 'manage_shop_order_posts_custom_column', 'acme_slot_column_value', 10, 2 );

function acme_slot_column( array $columns ): array {
    $columns['acme_slot'] = __( 'Delivery', 'acme-slots' );
    return $columns;
}

function acme_slot_column_value( string $column, $order_or_id ): void {
    if ( 'acme_slot' !== $column ) {
        return;
    }
    $order = $order_or_id instanceof WC_Order ? $order_or_id : wc_get_order( $order_or_id );
    if ( $order && $order->get_meta( '_acme_delivery_date' ) ) {
        echo esc_html( $order->get_meta( '_acme_delivery_date' ) . ' ' . $order->get_meta( '_acme_delivery_window' ) );
    }
}

add_filter( 'woocommerce_email_order_meta_fields', function ( array $fields, bool $sent_to_admin, WC_Order $order ): array {
    if ( $order->get_meta( '_acme_delivery_date' ) ) {
        $fields['acme_slot'] = [
            'label' => __( 'Delivery', 'acme-slots' ),
            'value' => $order->get_meta( '_acme_delivery_date' ) . ' ' . $order->get_meta( '_acme_delivery_window' ),
        ];
    }
    return $fields;
}, 10, 3 );

Both screens are covered in Admin Order Screens and Analytics Data. Email values are escaped by WooCommerce when it prints the fields. Releasing a slot: hook woocommerce_order_status_cancelled and woocommerce_order_status_failed and call Acme_Slots::release( $order_id ).

Runnable stand-in: slot validation messages

The shopper-facing text matters as much as the rule. This second example validates a posted value the way woocommerce_after_checkout_validation would, returning one precise message per problem instead of a generic failure:

PHP Validating a posted slot value

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the slot be validated again on the server when the checkout already shows only open slots?

    Between page load and submit another order may take the last seat, and posted values can be forged. The server decision is the only one that counts.
  2. 2. What protects capacity when two shoppers pick the last slot at the same moment?

    Validation alone cannot prevent a race. The reservation step must check and claim the seat in one atomic operation and report failure.
  3. 3. Which timezone should decide what counts as "tomorrow" or "after the cutoff"?

    The shop's delivery rules follow the shop's local clock, regardless of where the server or the shopper is.
  4. 4. Why register the admin column on two different hooks?

    With HPOS the list lives on a WooCommerce admin page with its own column hooks, while the legacy screen uses the shop_order post list hooks. Supporting both works on every store.
  5. 5. What should happen to a booked slot when its order is cancelled?

    Cancelled and failed orders no longer need the delivery seat, so the booking is released.

Summary

  • Slot rules (open days, cutoffs, capacity) belong in a testable engine; WooCommerce hooks call it.
  • Store bookings in a small indexed table and also on the order as meta; reserve atomically and release on cancel or failure.
  • Classic checkout uses woocommerce_checkout_fields; the block checkout uses the additional checkout fields API.
  • Validate server-side with clear messages, use the store timezone, and escape everything you print.
  • Show the slot in the HPOS and legacy admin lists and in emails.

Next: Project: Loyalty Points