Building a Custom WooCommerce Product Type from Scratch

A custom WooCommerce product type

WooCommerce ships with simple, variable, grouped and external products. A service with a booking date, a gift card or a license with seats does not fit any of them well, and storing “this simple product is actually a service” in a meta field leads to checks scattered all over the code. A product type of its own gives such products their own class, their own admin fields and their own add-to-cart behavior.

Problem: A shop sells consulting sessions. They are created as simple products with a meta flag, and a dozen snippets check that flag to hide the stock fields, skip shipping and add a date field to the cart form.

Solution: Register a product type ha_session in the type selector, map it to a class that extends WC_Product_Simple and declares itself virtual, show the price fields for it and add a “Session” tab in the product data panel, and render the normal add-to-cart form for it on the product page.

The class and the type

add_action( 'woocommerce_loaded', function (): void {
    class WC_Product_Ha_Session extends WC_Product_Simple {
        public function get_type() {
            return 'ha_session';
        }

        public function is_virtual() {
            return true; // no shipping
        }

        public function get_duration(): int {
            return (int) $this->get_meta( '_ha_duration' );
        }
    }
} );

add_filter( 'product_type_selector', function ( array $types ): array {
    $types['ha_session'] = __( 'Consulting session', 'textdomain' );
    return $types;
} );

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

The class is declared on woocommerce_loaded, because WC_Product_Simple must exist first. WooCommerce stores the type as a term of the product_type taxonomy and asks woocommerce_product_class which class to instantiate; from then on wc_get_product() returns a WC_Product_Ha_Session, and code checks $product->is_type( 'ha_session' ) instead of a meta flag. Extending the simple product keeps price, tax, sale and cart behavior; only what differs is overridden.

The admin fields

add_filter( 'woocommerce_product_data_tabs', function ( array $tabs ): array {
    $tabs['ha_session'] = array(
        'label'    => __( 'Session', 'textdomain' ),
        'target'   => 'ha_session_data',
        'class'    => array( 'show_if_ha_session' ),
        'priority' => 25,
    );
    $tabs['shipping']['class'][]  = 'hide_if_ha_session';
    $tabs['inventory']['class'][] = 'show_if_ha_session';
    return $tabs;
} );

add_action( 'woocommerce_product_data_panels', function (): void {
    echo '<div id="ha_session_data" class="panel woocommerce_options_panel hidden">';
    woocommerce_wp_text_input( array(
        'id'                => '_ha_duration',
        'label'             => __( 'Duration (minutes)', 'textdomain' ),
        'type'              => 'number',
        'custom_attributes' => array( 'min' => 15, 'step' => 15 ),
    ) );
    echo '</div>';
} );

add_action( 'woocommerce_admin_process_product_object', function ( WC_Product $product ): void {
    if ( $product->is_type( 'ha_session' ) && isset( $_POST['_ha_duration'] ) ) {
        $product->update_meta_data( '_ha_duration', absint( wp_unslash( $_POST['_ha_duration'] ) ) );
    }
} );

WooCommerce’s admin script shows and hides elements with the classes show_if_{type} and hide_if_{type} when the type select changes. The general price fields only carry show_if_simple and show_if_external, so they need the new class as well:

add_action( 'admin_footer', function (): void {
    if ( 'product' !== get_current_screen()->id ) {
        return;
    }
    echo "<script>jQuery( function ( $ ) { $( '.options_group.pricing' ).addClass( 'show_if_ha_session' ); $( '#product-type' ).trigger( 'change' ); } );</script>";
} );

woocommerce_admin_process_product_object runs before WooCommerce saves the product object, so the meta is saved with it; the nonce and capability checks of the product form have already happened at that point.

The product page

add_action( 'woocommerce_ha_session_add_to_cart', 'woocommerce_simple_add_to_cart' );

The single product template calls woocommerce_{type}_add_to_cart; without this line, products of the new type have no add-to-cart button. The simple product’s form is reused, and extra fields (a date picker for the session) are added with woocommerce_before_add_to_cart_button and stored as cart item data, the same technique as in a simple composite product.

NOTE: This is the classic product editor. The new block-based product editor that WooCommerce has been testing uses a different extension API (block templates), and product types from product_type_selector are not supported there. Existing products keep their type when the plugin is deactivated, but WooCommerce then falls back to the simple product class for an unknown type, so deactivation does not break the shop.