Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Real-World Projects

Project: Product Bundles

Build WooCommerce product bundles: a custom bundle product type, child items, price and stock rules, cart display and order item details, with a runnable stock and price engine.

A bundle is one product that is really several: a "Starter Kit" made of a mug, a notebook and a pen; a "Camera Set" with body, lens and bag. Customers see one price and one add-to-cart button, but the shop must still track stock for each part, ship all parts, and keep the books right. That makes bundles an excellent final project: they combine a custom product type, product data fields, price logic, stock logic, the cart and order items.

You will build the architecture and the rules for a simple fixed-contents bundle: one cart line for the bundle, with the child products stored as data. The real classes are read-only here (they need WooCommerce), and the rules for price and stock are in a plain-PHP engine you can run. Prerequisites: Custom Product Types, Working With Products in Code, The Cart and Session and Inventory Basics.

Decide the model first

There are two common ways to model a bundle in the cart, and the choice drives everything else:

Model Cart contents Stock Trade-off
Single line (this project) One line for the bundle; children shown as details You reduce child stock yourself when the order is placed Simple cart, clean totals; you own the stock logic
Parent plus child lines A bundle line plus a zero-price line per child WooCommerce reduces child stock by itself Lines must stay linked (removing the parent removes the children); reports and shipping show many lines

We choose the single line. It keeps the cart readable and prices simple, and the stock code is small and testable. The second model is what large bundle plugins do, and its extra complexity is mostly keeping the lines in sync.

flowchart TD
    A["Bundle product<br/>(type: bundle)"] --> B["Children<br/>[{id, qty}, ...]"]
    A --> C["Pricing mode<br/>fixed or sum minus %"]
    B --> D["Stock = min over children<br/>floor(stock / qty)"]
    B --> E["Cart: one line,<br/>children shown as details"]
    E --> F["Order placed:<br/>reduce each child's stock"]

The bundle's stock is never stored: it is derived from its children.

Step 1: register the product type

PHP
<?php
add_filter( 'product_type_selector', function ( array $types ): array {
    $types['acme_bundle'] = __( 'Bundle', 'acme-bundles' );
    return $types;
} );

add_filter( 'woocommerce_product_class', function ( string $classname, string $product_type ): string {
    return 'acme_bundle' === $product_type ? Acme_Product_Bundle::class : $classname;
}, 10, 2 );

class Acme_Product_Bundle extends WC_Product_Simple {

    public function get_type(): string {
        return 'acme_bundle';
    }

    /** @return array<int, array{id:int, qty:int}> */
    public function get_children_config(): array {
        $json = (string) $this->get_meta( '_acme_bundle_items' );
        $data = json_decode( $json, true );
        return is_array( $data ) ? $data : [];
    }
}

add_action( 'woocommerce_acme_bundle_add_to_cart', 'woocommerce_simple_add_to_cart' );

Extending WC_Product_Simple reuses its data store, add-to-cart form and admin behaviour (see Custom Product Types for the registry pieces, the data store mapping and the show/hide JavaScript for the product data panel). The last line reuses the simple product's add-to-cart template for our new type; the hook name is woocommerce_{type}_add_to_cart.

Step 2: the admin panel

Show a small repeater in the product data panel: a product search field and a quantity per row, plus a pricing mode. Save through the CRUD object and sanitize hard. The browser could send anything:

PHP
<?php
add_action( 'woocommerce_admin_process_product_object', function ( WC_Product $product ) {
    if ( 'acme_bundle' !== $product->get_type() ) {
        return;
    }
    $rows  = isset( $_POST['acme_bundle_items'] ) && is_array( $_POST['acme_bundle_items'] ) ? wp_unslash( $_POST['acme_bundle_items'] ) : [];
    $clean = [];
    foreach ( $rows as $row ) {
        $id  = absint( $row['id'] ?? 0 );
        $qty = max( 1, min( 99, absint( $row['qty'] ?? 1 ) ) );
        $child = $id ? wc_get_product( $id ) : false;
        if ( $child && $id !== $product->get_id() && 'acme_bundle' !== $child->get_type() ) {   // no nesting, no self reference
            $clean[ $id ] = [ 'id' => $id, 'qty' => $qty ];
        }
    }
    $product->update_meta_data( '_acme_bundle_items', wp_json_encode( array_values( $clean ) ) );
    $mode = isset( $_POST['acme_bundle_mode'] ) && 'sum' === $_POST['acme_bundle_mode'] ? 'sum' : 'fixed';
    $product->update_meta_data( '_acme_bundle_mode', $mode );
    $product->update_meta_data( '_acme_bundle_percent', min( 90, absint( $_POST['acme_bundle_percent'] ?? 0 ) ) );
} );

Two guards worth copying: no bundles inside bundles (a cycle or deep tree would make stock and price calculations explode), and duplicate children are merged by keying on the id. Capability and nonce checks are done by WooCommerce when it saves a product; your job is the data. See Custom Product Fields and Tabs.

Step 3: the pricing and stock engine (runnable)

Price and stock are the rules where bundles usually go wrong, so they live in a class without WordPress dependencies. Two pricing modes:

  • fixed: the bundle has its own price (the regular price field), whatever the children cost.
  • sum: the price is the sum of the children's prices times their quantities, minus a percentage. The price follows child price changes.

Stock is derived: the number of complete bundles you can build is the minimum, over all children, of floor(child stock / quantity needed). A child with unlimited stock (not managed) never limits the bundle.

PHP Bundle price and stock 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.

Check the numbers: the kit sums to 12.00 + 8.00 + 2 x 2.50 + 3 x 1.00 = 28.00, and 15% off gives 23.80. The notebook limits the kit (7 notebooks), and the sticker, which has no stock management, never limits anything. A failed reserve() changes nothing: it checks first and only then subtracts, which matters when several children could be short.

Step 4: purchasability and the cart

The bundle's own stock status must follow its children, otherwise the shop sells bundles it cannot build:

PHP
<?php
class Acme_Product_Bundle extends WC_Product_Simple {
    // ... get_type(), get_children_config() as before

    public function is_in_stock(): bool {
        return Acme_Bundle_Engine::available( $this->get_children_config() ) !== 0;
    }

    public function get_price( $context = 'view' ) {
        if ( 'sum' === $this->get_meta( '_acme_bundle_mode' ) ) {
            return Acme_Bundle_Engine::sum_price( $this->get_children_config(), (int) $this->get_meta( '_acme_bundle_percent' ) ) / 100;
        }
        return parent::get_price( $context );
    }
}

add_filter( 'woocommerce_add_to_cart_validation', function ( bool $passed, int $product_id, int $quantity ): bool {
    $product = wc_get_product( $product_id );
    if ( $product instanceof Acme_Product_Bundle ) {
        $available = Acme_Bundle_Engine::available( $product->get_children_config() );
        if ( null !== $available && $quantity > $available ) {
            wc_add_notice( sprintf( __( 'Only %d of this bundle can be made right now.', 'acme-bundles' ), $available ), 'error' );
            return false;
        }
    }
    return $passed;
}, 10, 3 );

Note the cost: computing a sum price or stock loads every child product. That is fine on a product page but can hurt on a category page with 100 bundles. Cache the derived values per bundle in a transient (or the object cache) and clear it when a child product changes (woocommerce_product_set_stock, woocommerce_update_product); see Performance and Scaling Large Stores.

Remember to also check stock again when the order is placed, not only when adding to the cart: the cart may be hours old.

Step 5: show the contents in cart and order

PHP
<?php
add_filter( 'woocommerce_get_item_data', function ( array $item_data, array $cart_item ): array {
    $product = $cart_item['data'];
    if ( $product instanceof Acme_Product_Bundle ) {
        foreach ( $product->get_children_config() as $child ) {
            $p = wc_get_product( $child['id'] );
            if ( $p ) {
                $item_data[] = [
                    'key'   => __( 'Includes', 'acme-bundles' ),
                    'value' => sprintf( '%d x %s', $child['qty'] * $cart_item['quantity'], wp_strip_all_tags( $p->get_name() ) ),
                ];
            }
        }
    }
    return $item_data;
}, 10, 2 );

add_action( 'woocommerce_checkout_create_order_line_item', function ( WC_Order_Item_Product $item, string $cart_item_key, array $values ) {
    $product = $values['data'];
    if ( $product instanceof Acme_Product_Bundle ) {
        $item->add_meta_data( '_acme_bundle_items', wp_json_encode( $product->get_children_config() ), true );   // hidden record
        $item->add_meta_data( __( 'Includes', 'acme-bundles' ), implode( ', ', array_map( fn( $c ) => $c['qty'] . ' x #' . $c['id'], $product->get_children_config() ) ), true );
    }
}, 10, 3 );

The hidden meta (leading underscore) snapshots the contents at order time. If the shop changes the bundle next month, old orders must still say what was sold; never rebuild an old order's contents from the live bundle. The visible meta shows up in the order details, emails and the admin screen.

Step 6: reduce and restore stock

When an order's stock is reduced, add the children. When the order is cancelled and stock is restored, give the children back:

PHP
<?php
add_action( 'woocommerce_reduce_order_stock', function ( WC_Order $order ) {
    foreach ( $order->get_items() as $item ) {
        $children = json_decode( (string) $item->get_meta( '_acme_bundle_items' ), true );
        foreach ( is_array( $children ) ? $children : [] as $child ) {
            $product = wc_get_product( $child['id'] );
            if ( $product && $product->managing_stock() ) {
                wc_update_product_stock( $product, $child['qty'] * $item->get_quantity(), 'decrease' );
            }
        }
    }
} );
// A matching 'woocommerce_restore_order_stock' handler uses 'increase'.

WooCommerce marks the order when it reduces stock (_order_stock_reduced), so this action runs once per order, not once per status change. Test refunds and partial cancellations: restoring all children for a partial refund would be wrong, so decide the policy (the bundle is returned whole or not at all is a sensible rule).

Runnable stand-in: the order record and stock history

The second example plays out the order life cycle: reserve on placing, restore on cancelling, and a snapshot that keeps old orders stable after the bundle is edited.

PHP Order snapshot and stock restore

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.

Without the snapshot, cancelling after the edit would restore two mugs per bundle instead of one and inflate the stock.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many complete bundles can be built from children with stock 10 (needs 2 each) and 7 (needs 1 each)?

    The first child allows floor(10 / 2) = 5 bundles and the second allows 7. The bundle stock is the minimum, 5.
  2. 2. Why is the bundle's stock calculated instead of stored?

    Child stock changes through many paths. Deriving the bundle stock from its children keeps one source of truth.
  3. 3. Why save a snapshot of the contents on the order item?

    Orders are historical records. Rebuilding them from the live bundle would change the past and give wrong stock restores.
  4. 4. Which guard prevents infinite loops in price and stock calculations?

    Nested or self-referencing bundles create cycles. Refusing them at save time keeps the calculations simple and finite.
  5. 5. When must bundle stock be checked besides adding to cart?

    Stock changes while the cart waits. The decisive check is at order time, together with the reservation.

Summary

  • Choose the cart model first; a single bundle line with children as data is the simplest.
  • Register a custom product type that extends WC_Product_Simple, and reuse its add-to-cart template with woocommerce_{type}_add_to_cart.
  • Sanitize child lists on save: integers, bounded quantities, no self reference or nesting.
  • Derive bundle stock as the minimum of floor(child stock / quantity); compute price in cents with one rounding step.
  • Show contents with woocommerce_get_item_data and order item meta, snapshot them on the order, and reduce and restore child stock through the stock hooks.

Next: Exercises With Solutions