Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Orders and Checkout

Cart and Checkout Blocks Extensibility

Extend the block-based WooCommerce cart and checkout: Store API extension data, update callbacks, checkout filters, additional fields and block compatibility.

Newer WooCommerce stores use the Cart and Checkout blocks instead of the old [woocommerce_cart] and [woocommerce_checkout] shortcodes. They look similar to shoppers, but they are built in a completely different way, and that changes how you extend them. Most of the PHP hooks from Classic Checkout Fields and Validation are simply not called by the blocks. Instead, the blocks are React components that talk to a JSON API called the Store API, and you extend them through that API and through a small set of JavaScript registries.

This lesson maps the architecture, then walks through the four extension tools you will use most: extension data on the Store API, update callbacks, checkout filters and additional checkout fields. It also explains how to tell WooCommerce that your plugin (especially a payment gateway) works with the blocks. The real code needs WordPress, WooCommerce and a JavaScript build, so it is read-only here; the runnable stand-ins reproduce the shape of the data exchange in plain PHP and say clearly what is real.

How the blocks work

flowchart LR
    A["Cart / Checkout block<br/>(React in the browser)"] -->|"GET and POST<br/>/wc/store/v1/..."| B["Store API<br/>(PHP routes and schemas)"]
    B --> C["WC_Cart, WC_Customer,<br/>WC_Order"]
    D["Your PHP: endpoint data,<br/>update callbacks"] --> B
    E["Your JS: filters,<br/>slot fills, payment method"] --> A

The browser never renders the cart from PHP templates: it renders whatever the Store API returns.

Three consequences follow:

  • No server-rendered template hooks. Actions such as woocommerce_before_checkout_form or filters such as woocommerce_checkout_fields belong to the shortcode templates. The block checkout does not run them.
  • The cart is recalculated through the same engine. Price hooks like woocommerce_before_calculate_totals still apply (see Dynamic Pricing, Fees and Discounts), because the Store API loads the same WC_Cart.
  • The page is a snapshot of an API response. If you want your data in the UI, put it in the API response; if the UI should change something on the server, call an API route.

The Store API is meant for storefronts. Its routes live under /wp-json/wc/store/v1/ (cart, checkout, products). It is public, identified by a nonce or a cart token instead of API keys, and is covered in The REST API and the Store API.

Adding data to the API response

To show something custom in the cart (a delivery estimate, a loyalty-point preview), first expose it as extension data. You register a namespace and two callbacks: one that returns the data and one that describes its schema. The first argument names which endpoint to extend (the cart here):

PHP
<?php
use Automattic\WooCommerce\StoreApi\Schemas\V1\CartSchema;

add_action( 'woocommerce_init', function () {
    if ( ! function_exists( 'woocommerce_store_api_register_endpoint_data' ) ) {
        return;
    }

    woocommerce_store_api_register_endpoint_data( [
        'endpoint'        => CartSchema::IDENTIFIER,
        'namespace'       => 'acme-loyalty',
        'data_callback'   => function () {
            $cart = WC()->cart;
            return [
                'points_preview' => (int) floor( (float) $cart->get_subtotal() ),
            ];
        },
        'schema_callback' => function () {
            return [
                'points_preview' => [
                    'description' => __( 'Points earned by this order.', 'acme' ),
                    'type'        => 'integer',
                    'readonly'    => true,
                ],
            ];
        },
        'schema_type'     => ARRAY_A,
    ] );
} );

The response then contains "extensions": { "acme-loyalty": { "points_preview": 42 } }. Always use a unique, prefixed namespace so plugins do not collide. The schema callback is not decoration: it documents the field and lets the API validate and describe it.

Letting the browser change server state

Reading is half the job. If the shopper ticks "gift wrap" in your UI, the server must know. The blocks provide extensionCartUpdate() on the JavaScript side and an update callback on the PHP side. In the browser (read-only, needs a build step with @wordpress/scripts):

JavaScript
import { extensionCartUpdate } from '@woocommerce/blocks-checkout';

export function setGiftWrap( enabled ) {
    return extensionCartUpdate( {
        namespace: 'acme-giftwrap',
        data: { enabled },
    } );
}

On the server you register the matching callback:

PHP
<?php
add_action( 'woocommerce_init', function () {
    if ( ! function_exists( 'woocommerce_store_api_register_update_callback' ) ) {
        return;
    }

    woocommerce_store_api_register_update_callback( [
        'namespace' => 'acme-giftwrap',
        'callback'  => function ( array $data ) {
            $enabled = ! empty( $data['enabled'] );
            WC()->session->set( 'acme_giftwrap', $enabled ? 'yes' : 'no' );
            // After the callback, WooCommerce recalculates the cart and returns it.
        },
    ] );
} );

Then a normal fee hook reads the session value and calls add_fee(). The browser receives the refreshed cart and re-renders the totals. Treat the $data array as untrusted input, exactly like $_POST: validate types and values, because anyone can call the Store API directly.

Changing how things display: checkout filters

For purely visual tweaks (renaming a line item, adding a CSS class, changing the subtotal format) the blocks offer checkout filters. These are JavaScript only:

JavaScript
import { registerCheckoutFilters } from '@woocommerce/blocks-checkout';

registerCheckoutFilters( 'acme-loyalty', {
    cartItemClass: ( value, extensions, args ) => {
        const isGift = extensions?.[ 'acme-giftwrap' ]?.is_gift;
        return isGift ? `${ value } is-gift` : value;
    },
} );

Each filter receives the current value and returns a new one; it must always return a value of the same type, even when it changes nothing. Which filter names exist (item name, class, subtotal format, totals labels and so on) depends on the WooCommerce version, so check the documentation of the version you target. Filters never change what is charged: they change presentation only, and the money rules stay on the server.

Slot fills and inner blocks

To insert whole components, the blocks use slots and fills: the block declares a slot, you render a fill into it. Names such as ExperimentalOrderMeta and ExperimentalDiscountsMeta have been exposed by @woocommerce/blocks-checkout for this, and the "Experimental" prefix is an honest signal that they have changed between releases. A more stable route for larger features is to ship your own inner block that the merchant can place inside the checkout in the block editor. Either way, read the data from the store the blocks provide, and send changes with extensionCartUpdate().

Additional checkout fields

Where the classic checkout used woocommerce_checkout_fields, recent WooCommerce versions offer a server-side API to register extra fields for the block checkout. You declare the field and WooCommerce renders it, validates it and saves it with the order or customer:

PHP
<?php
add_action( 'woocommerce_init', function () {
    if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
        return; // Older WooCommerce: the feature is not available.
    }

    woocommerce_register_additional_checkout_field( [
        'id'       => 'acme/delivery-note',
        'label'    => __( 'Delivery note', 'acme' ),
        'location' => 'order',     // 'contact', 'address' or 'order'
        'type'     => 'text',
        'required' => false,
    ] );
} );

The field ids are namespaced (vendor/name), the location chooses which section of the checkout shows it, and the saved value is stored in order meta that you read through the CRUD API (see Orders and High-Performance Order Storage). Field types are limited (text, select, checkbox), which is a deliberate trade for consistent accessibility and validation. For anything the API cannot express, use an inner block plus an update callback.

Server-side checkout hooks

When the shopper presses "Place order", the blocks call the checkout route of the Store API. A few actions let you step in on the server: for example woocommerce_store_api_checkout_update_order_from_request runs while the order is being filled from the request and is the place to copy validated extension data onto the order, and woocommerce_store_api_checkout_order_processed runs after the order exists. To reject an order, throw a \Automattic\WooCommerce\StoreApi\Exceptions\RouteException with a message and an error code; the blocks display the message. Confirm the exact hook names for your minimum WooCommerce version before relying on them.

Declaring compatibility, especially for gateways

A plugin that has not been tested with the blocks should say so, and one that has should declare it. In your main file:

PHP
<?php
add_action( 'before_woocommerce_init', function () {
    if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            'cart_checkout_blocks',
            __FILE__,
            true
        );
    }
} );

Declaring it is a promise, not a feature. A payment gateway also needs a block integration: a PHP class extending AbstractPaymentMethodType (registered on woocommerce_blocks_payment_method_type_registration) that says whether the method is active and which script to load, plus a JavaScript call to registerPaymentMethod() that renders the label and the payment form. Without it your gateway simply does not appear in the block checkout, which is the most common "my gateway vanished" report. Gateway basics are in Building a Payment Gateway.

Classic versus blocks at a glance

Task Classic (shortcode) Blocks
Add a field woocommerce_checkout_fields woocommerce_register_additional_checkout_field
Validate woocommerce_checkout_process Field validation hooks, RouteException in Store API hooks
Show custom UI Template hooks Inner blocks, slot fills
Change cart state from the UI Form post and page reload extensionCartUpdate()
Rename or restyle items Template or filter in PHP registerCheckoutFilters()

Runnable stand-ins

There is no Store API or React here. These examples model the payload shape in plain PHP: real is the idea (an extensions object keyed by namespace, an update callback that must validate input); stand-in is the code, which is ordinary PHP.

PHP Cart payload with extension data

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.

The extensions object is the part your plugin owns. Everything else in a real response is produced by WooCommerce.

PHP Update callbacks must validate their input

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.

Only the first request changes the state. The second is rejected because the type is wrong, and the third because nobody registered that namespace. Real callbacks should be this strict, since the Store API is reachable by anyone with a browser.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a custom field added with woocommerce_checkout_fields not appear in the block-based checkout?

    The Cart and Checkout blocks are React components that render API responses. The classic filters belong to the shortcode templates, so for blocks you use the additional checkout fields API or an inner block.
  2. 2. What is the job of the PHP update callback registered for a namespace?

    The browser sends a namespace and a data object, and the callback applies it on the server. Because anyone can call the API, the data must be validated.
  3. 3. A payment gateway works in the classic checkout but is missing from the block checkout. What is the most likely cause?

    Blocks do not render the classic payment fields. A gateway must register a payment method integration so the blocks know how to show and submit it.
  4. 4. What can registerCheckoutFilters() safely be used for?

    Checkout filters are JavaScript display filters. Money and validation rules must stay on the server, where they cannot be bypassed.

Summary

  • The Cart and Checkout blocks render Store API responses in React; the shortcode hooks and templates are not used.
  • Expose your data with Store API extension data under a unique namespace, and describe it with a schema.
  • Change server state from the UI with extensionCartUpdate() plus a PHP update callback that validates its input.
  • Use registerCheckoutFilters() and slot fills for presentation only; use the additional checkout fields API for simple fields.
  • Declare cart_checkout_blocks compatibility honestly, and give every gateway a block integration.
  • The stand-ins model the payload shape and validation; the real APIs need WooCommerce and a JavaScript build.

Next: Building a Payment Gateway