Extending the WooCommerce REST API with Custom Routes and Fields

Extend the WooCommerce REST API: extra fields and custom routes

An ERP or a mobile app talks to WooCommerce through /wp-json/wc/v3/. Sooner or later it needs data that WooCommerce does not expose: an internal supplier code on products, a B2B account number on customers, or a resource of the plugin itself. There are two clean ways: add fields to existing WooCommerce responses with register_rest_field(), and register new routes in the plugin’s own namespace that use the same authentication as the WooCommerce API.

Problem: An ERP integration reads products through the WooCommerce REST API and needs the supplier code stored in the product meta _ha_supplier_code. It currently reads the whole meta_data array of each product and filters it on its side, and writing the code back is not possible at all.

Solution: Register a supplier_code field on the product object type with get_callback, update_callback and a schema, so it is readable and writable in wc/v3/products. For data that is not a product, order or customer, add a route in an own namespace with a capability-based permission_callback; WooCommerce’s API keys authenticate it as well.

An extra field on products

add_action( 'rest_api_init', function (): void {
    register_rest_field( 'product', 'supplier_code', array(
        'get_callback'    => function ( array $product ): string {
            return (string) get_post_meta( $product['id'], '_ha_supplier_code', true );
        },
        'update_callback' => function ( $value, $product ): bool {
            $wc_product = $product instanceof WC_Product ? $product : wc_get_product( $product->ID ?? 0 );
            if ( ! $wc_product ) {
                return false;
            }
            $wc_product->update_meta_data( '_ha_supplier_code', sanitize_text_field( $value ) );
            $wc_product->save_meta_data();
            return true;
        },
        'schema'          => array(
            'description' => __( 'Supplier code.', 'textdomain' ),
            'type'        => 'string',
            'context'     => array( 'view', 'edit' ),
        ),
    ) );
} );

The object type product is the type WooCommerce’s controllers use for wc/v3/products; for orders it is shop_order, for customers customer. The field appears in every product response, can be requested with ?_fields=id,sku,supplier_code, and is accepted in PUT /wc/v3/products/123 with {"supplier_code": "AC-4411"}. The permission is the one of the products endpoint: a key with read access can read, a key with write access can write. Writing through the product object instead of update_post_meta() keeps WooCommerce’s caches and lookup tables in sync. The same function on core post types: register_rest_field.

A route of your own

add_action( 'rest_api_init', function (): void {
    register_rest_route( 'ha-b2b/v1', '/accounts/(?P<customer_id>\d+)', array(
        'methods'             => WP_REST_Server::READABLE,
        'permission_callback' => fn() => current_user_can( 'manage_woocommerce' ),
        'callback'            => function ( WP_REST_Request $request ) {
            $customer = new WC_Customer( (int) $request['customer_id'] );
            if ( ! $customer->get_id() ) {
                return new WP_Error( 'ha_no_customer', 'Customer not found.', array( 'status' => 404 ) );
            }
            return array(
                'customer_id'    => $customer->get_id(),
                'account_number' => $customer->get_meta( 'ha_account_number' ),
                'credit_limit'   => (float) $customer->get_meta( 'ha_credit_limit' ),
            );
        },
    ) );
} );

WooCommerce authenticates requests with consumer key and secret for all routes under /wp-json/, not only its own: over HTTPS with Basic Auth, the request runs as the user who owns the key, and current_user_can() checks that user’s capabilities. The key’s read/write permission is checked only by WooCommerce’s own routes; for custom routes, the capability check is the protection. A plugin’s own namespace (ha-b2b/v1) avoids collisions with future WooCommerce routes. Controllers for larger APIs: REST API controllers with WP_REST_Controller.

Test

curl -s -u ck_xxx:cs_xxx "https://shop.example.com/wp-json/wc/v3/products/123?_fields=id,sku,supplier_code"
curl -s -u ck_xxx:cs_xxx -X PUT -H "Content-Type: application/json" \
    -d '{"supplier_code":"AC-4411"}' "https://shop.example.com/wp-json/wc/v3/products/123"

NOTE: For the visitor-facing cart and checkout, the Store API (wc/store/v1) is the API to extend, with woocommerce_store_api_register_endpoint_data() instead of register_rest_field(); it has no API keys and runs with the visitor’s session. The basics of both APIs: the WooCommerce REST API for a headless storefront.