Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Products and the CRUD Layer

Custom Product Types

Register a custom WooCommerce product type: the selector, a WC_Product subclass, the data store map, the add-to-cart template, admin panel JS and purchase rules.

Simple, variable, grouped and external products cover most shops. When they do not, for example for a rental that needs dates, a donation with a free amount or a bundle of other products, you can add your own product type. A type is more than a label: it decides which PHP class represents the product, which admin panels are visible, how the add-to-cart area looks and when the product may be bought.

Because a type touches the admin, the data layer and the storefront, it is the most "full-stack" thing you will build in this chapter. This lesson walks through each piece in order. It assumes you know the CRUD layer from CRUD Classes and Data Stores and the product fields from Custom Product Fields and Tabs. The real registration code is read-only; the stand-in is a small registry that shows how a type name is resolved to a class, a data store and rules.

Before building a type, ask whether a simple product plus custom fields (and perhaps some cart logic) would do. A custom type is justified when the behaviour of the product itself differs, not just its data. Every extension that touches product types has to know about yours, so each new type adds maintenance cost.

What a product type consists of

flowchart TD
    A["Type slug<br/>acme_rental"] --> B["product_type_selector<br/>(label in the dropdown)"]
    A --> C["woocommerce_product_class<br/>(slug to PHP class)"]
    C --> D["WC_Product_Acme_Rental<br/>(get_type, rules)"]
    A --> E["woocommerce_data_stores<br/>(product-acme_rental)"]
    A --> F["woocommerce_acme_rental_add_to_cart<br/>(storefront form)"]
    A --> G["Admin JS<br/>(show_if_acme_rental panels)"]

One slug links five integration points. Missing any of them gives a half-working type.

Step 1: the selector

The "Product data" drop-down on the edit screen is built from the product_type_selector filter. Add your slug and label:

PHP
add_filter( 'product_type_selector', function ( array $types ): array {
    $types['acme_rental'] = __( 'Rental product', 'acme-rental' );
    return $types;
} );

The slug is stored as a term of the product_type taxonomy on each product. Pick a prefixed, lowercase slug (acme_rental) so it cannot collide with another plugin's type. Many plugins also make sure the term exists when they activate, using term_exists() and wp_insert_term() against the product_type taxonomy; WooCommerce also assigns the term when a product of that type is saved.

Step 2: the class

The class extends WC_Product (or WC_Product_Simple if you want simple behaviour and only tweak it). The key method is get_type():

PHP
class WC_Product_Acme_Rental extends WC_Product_Simple {

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

    public function get_price_per_day( string $context = 'view' ): string {
        return (string) $this->get_prop( 'price', $context );
    }

    public function is_purchasable(): bool {
        // Only offer rentals that have a daily price and are published.
        return apply_filters(
            'woocommerce_is_purchasable',
            $this->exists() && 'publish' === $this->get_status() && '' !== $this->get_price(),
            $this
        );
    }
}

WooCommerce must be told which class belongs to which slug. Its default guess builds a name such as WC_Product_Acme_rental from the slug, which is fragile with underscores, so use the filter and be explicit:

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

After this, wc_get_product( $id ) returns an instance of your class for any product of that type. Everything in the cart, the REST API and the admin that asks the factory for a product benefits.

Step 3: the data store

Each WC_Product loads a data store named product- plus its type. For your slug that is product-acme_rental, and it is not in WooCommerce's list. Map it, usually to the default product store, so saving and reading work like any simple product:

PHP
add_filter( 'woocommerce_data_stores', function ( array $stores ): array {
    $stores['product-acme_rental'] = 'WC_Product_Data_Store_CPT';
    return $stores;
} );

Reusing the default store is the safe choice because it also maintains the lookup tables and the price fields the shop depends on. A custom store is only needed when the type's data lives somewhere else entirely, as discussed in the CRUD lesson.

Step 4: admin panels and JavaScript

WooCommerce's admin script shows and hides panels depending on the selected type, using the CSS classes show_if_{type} and hide_if_{type}. The built-in General tab fields (price, sale price) carry show_if_simple, so they vanish for a type it has never heard of. Your plugin must add the class to the elements that should remain visible, with a small script loaded on the product edit screen:

JavaScript
// assets/admin-product.js, enqueued only on the product edit screen
jQuery( function ( $ ) {
    // Reuse the built-in price fields and inventory for the rental type.
    $( '.options_group.pricing' ).addClass( 'show_if_acme_rental' );
    $( '.inventory_options' ).addClass( 'show_if_acme_rental' );
    $( '.options_group.show_if_simple' ).addClass( 'show_if_acme_rental' );

    // Re-run the show/hide logic for the currently selected type.
    $( 'select#product-type' ).trigger( 'change' );
} );

Your own fields from a custom tab or panel use the same classes, for instance 'class' => [ 'show_if_acme_rental' ] in the woocommerce_product_data_tabs entry. Enqueue the script only on product screens, and check get_current_screen() so it does not load on every admin page.

Step 5: the add-to-cart area

On the product page, WooCommerce prints the add-to-cart area by firing an action named after the product type: woocommerce_{type}_add_to_cart. For built-in types the theme has templates under single-product/add-to-cart/. For yours, hook the action and print a form:

PHP
add_action( 'woocommerce_acme_rental_add_to_cart', function (): void {
    global $product;
    ?>
    <form class="cart" method="post" enctype="multipart/form-data">
        <label for="acme-days"><?php esc_html_e( 'Days', 'acme-rental' ); ?></label>
        <input id="acme-days" name="acme_days" type="number" min="1" value="1">
        <button type="submit" name="add-to-cart" value="<?php echo esc_attr( (string) $product->get_id() ); ?>"
                class="single_add_to_cart_button button alt">
            <?php echo esc_html( $product->single_add_to_cart_text() ); ?>
        </button>
    </form>
    <?php
} );

The posted field acme_days is not yet connected to the cart. Reading it, validating it and saving it as cart item data is covered in The Cart and Session. If you want ordinary simple-product behaviour and only a different form, you can also print the simple form from woocommerce_simple_add_to_cart inside your hook. WooCommerce falls back to its simple add-to-cart handling for unknown types, which is why a type based on the simple class "just works" for plain quantity buying.

Pricing and purchasability rules

Two methods on the product class carry most of a type's business rules:

  • is_purchasable() decides whether a product can be added to the cart at all. The cart, the shop loop's buttons and the REST API all ask it. Always route your result through the woocommerce_is_purchasable filter, like the example above, so other plugins can still adjust it.
  • get_price() (and the 'view' price filters, which are described in Dynamic Pricing, Fees and Discounts) decide what the shopper pays. For the rental, the line price per day multiplied by the chosen days belongs in cart code, not in the product class, because the product does not know the days until someone picks them.

Other methods you may override are is_sold_individually(), is_virtual(), is_downloadable(), add_to_cart_text() and add_to_cart_url(). Override only what differs from the parent class.

A registry stand-in

Everything above is "look up by slug": slug to label, slug to class, slug to data store, slug to rules. The stand-in implements that lookup with a registry and a factory, so you can see why leaving one entry out breaks the type.

PHP A product-type registry and factory (stand-in)

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.

What is real: slugs map to labels, classes and stores, and a missing store mapping is a classic cause of errors when a custom product is loaded. What is the stand-in: WooCommerce spreads this across several filters and the factory, and its fallback for an unknown type is more involved than the one shown here.

Purchasability and rental pricing

The type's rules are plain methods, so you can test them without WordPress. This second stand-in keeps the rental price in integer cents and checks the same conditions that is_purchasable() checks above, plus the price for a number of days that would live in cart item data.

PHP Rental price and purchasability rules (stand-in)

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.

What is real: purchasability is a boolean method on the product class, and the number of days arrives through cart item data. What is the stand-in: the tiered rental discount is an invented rule, and WooCommerce would apply the final amount in a cart price hook.

Testing the finished type

Check this list before you ship a custom type:

  1. Create a product of the type, save it, reload the edit screen: is the type still selected and are the right panels visible?
  2. Open the product page as a guest: does the add-to-cart form appear and work?
  3. Add it to the cart, check out, then look at the order line: is your cart item data there?
  4. Fetch the product through the REST API and through wc_get_products( [ 'type' => 'acme_rental' ] ).
  5. Deactivate the plugin: how do existing products of this type behave? A type disappearing leaves products that WooCommerce treats as another type, so document this and consider converting them in your uninstall routine.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which filter adds a new entry to the Product data drop-down?

    product_type_selector returns the array of slug => label that fills the drop-down. The other filters map the slug to classes and stores.
  2. 2. Which key does a product of type "acme_rental" use to look up its data store?

    The product class asks the data store loader for "product-" followed by its type, so you add that key to woocommerce_data_stores.
  3. 3. What hook prints the add-to-cart area for your type on the product page?

    The product page fires an action named woocommerce_{type}_add_to_cart.
  4. 4. Why route is_purchasable() through the woocommerce_is_purchasable filter?

    Core methods apply that filter, and extensions expect it. Skipping it makes your type behave differently from every other product.
  5. 5. Why do the standard price fields disappear for a custom type?

    Admin panels are shown by CSS class according to the selected type, so you must add your type's class to the panels you want to keep.

Summary

  • A product type is a slug wired to five places: the selector, a WC_Product subclass, the data store map, admin panel visibility and the add-to-cart hook.
  • Map the slug to a class with woocommerce_product_class and to a store with the product-{slug} key in woocommerce_data_stores.
  • Reuse WC_Product_Data_Store_CPT unless the data truly lives elsewhere.
  • Use show_if_{type} classes and a small admin script to keep needed panels visible.
  • Put purchase rules in is_purchasable() and keep the woocommerce_is_purchasable filter in the chain.
  • Keep rental-style inputs (such as days) in cart item data rather than in the product class.

Next: The Cart and Session