Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Your First WooCommerce Extension

Build a minimal WooCommerce extension the right way: plugin header, active-plugin checks, HPOS compatibility declaration, a safe bootstrap and one hooked feature.

A WooCommerce extension is a normal WordPress plugin that depends on another plugin. That dependency is the whole difficulty of a first extension: your code must not run (and must not crash the site) when WooCommerce is missing, too old, or not loaded yet. A good skeleton handles those cases before it does anything useful.

In this lesson you build the skeleton: the plugin header, the activation check, the compatibility declaration that tells WooCommerce your plugin understands its newer features, the bootstrap on the right hook, and one small feature that proves the wiring works. If plugin files, hooks and classes are new to you, read Your First Plugin and Plugin Structure and Object-Oriented Plugins first. The map of layers from How WooCommerce Is Built explains why we stay on the hook layer.

WordPress and WooCommerce cannot run on this site, so the plugin code below is read-only. The runnable examples are plain PHP stand-ins that simulate the loading order and the guard logic. They are not WordPress code.

The plugin header

The comment block at the top of the main file is what WordPress reads. For an extension it carries a few extra lines:

PHP
<?php
/**
 * Plugin Name:       Acme Shipping Note
 * Description:       Shows a delivery promise on product pages.
 * Version:           1.0.0
 * Requires at least: 6.5
 * Requires PHP:      8.1
 * Requires Plugins:  woocommerce
 * WC requires at least: 9.0
 * WC tested up to:   10.0
 * Text Domain:       acme-shipping-note
 * License:           GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;
  • Requires Plugins: woocommerce (WordPress 6.5 and later) makes WordPress refuse to activate your plugin until WooCommerce is installed and active, and it blocks deactivating WooCommerce while your plugin is active. The value is the plugin's directory slug.
  • WC requires at least and WC tested up to are read by WooCommerce itself. They feed the compatibility information on its screens and in the status tooling. They do not prevent activation, so they are documentation, not protection.
  • defined( 'ABSPATH' ) || exit; stops anyone from running the file directly through the web server.

Do not rely on the header alone. Plugins can be activated by WP-CLI, by must-use code or from an old backup, and the requirement is only enforced in the admin activation flow of newer WordPress versions. Your code still checks at runtime.

Check that WooCommerce is available

The classic and still reliable check is whether the main class exists, done after all plugins have loaded:

PHP
<?php
add_action( 'plugins_loaded', 'acme_sn_boot', 20 );

function acme_sn_boot(): void {
    if ( ! class_exists( 'WooCommerce' ) ) {
        add_action( 'admin_notices', 'acme_sn_missing_woocommerce_notice' );
        return;
    }

    if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '9.0', '<' ) ) {
        add_action( 'admin_notices', 'acme_sn_old_woocommerce_notice' );
        return;
    }

    require_once __DIR__ . '/includes/class-acme-sn-plugin.php';
    Acme_SN_Plugin::instance()->init();
}

function acme_sn_missing_woocommerce_notice(): void {
    if ( ! current_user_can( 'activate_plugins' ) ) {
        return;
    }
    echo '<div class="notice notice-error"><p>';
    echo esc_html__( 'Acme Shipping Note needs WooCommerce to be active.', 'acme-shipping-note' );
    echo '</p></div>';
}

Why plugins_loaded? Every active plugin file has been included by then, so class_exists( 'WooCommerce' ) gives the true answer regardless of alphabetical load order. Checking at the top level of your file would fail whenever your plugin loads before WooCommerce. The priority 20 simply runs after the default 10, which is where many plugins bootstrap.

Notice what the guard does when WooCommerce is missing: it returns before requiring any class file, so none of your code that extends or calls WooCommerce classes is ever parsed in a broken environment. That matters, because a class declared with extends WC_Payment_Gateway is a fatal error if the parent does not exist.

Two older patterns to avoid: scanning get_option( 'active_plugins' ) (it misses network-activated plugins on multisite and plugins in unusual folders) and calling deactivate_plugins() from inside your boot function (surprising and hard to debug). Showing an admin notice and doing nothing else is the polite default.

Declare feature compatibility

WooCommerce has opt-in features. The two that matter most to extension authors are High-Performance Order Storage (orders in their own tables) and the block-based cart and checkout. WooCommerce shows a warning for plugins that have not declared compatibility, and a store owner enabling HPOS will be told your plugin is incompatible unless you declare it. You declare it on the before_woocommerce_init hook:

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

Three details:

  • The hook fires early, before WooCommerce initializes its features. Register the callback when your main file loads (the top level of the file), as WooCommerce recommends, instead of inside a later hook: a callback added after the hook has already fired is never called, and relying on exact timing is fragile.
  • The second argument is the path of your main plugin file; the third is true for "compatible" and false for "explicitly not compatible".
  • A declaration is a promise, not a magic switch. Declare custom_order_tables only after you have checked that your code reads and writes orders through the order API and never through get_post_meta() on an order ID. Orders are covered in depth in Orders and High-Performance Order Storage. Declare cart_checkout_blocks only if your features work with the block checkout, which does not run the classic checkout hooks; see Cart and Checkout Blocks Extensibility.

A first hooked feature

With the guard in place, add something small. This class prints a delivery promise on classic single-product pages:

PHP
<?php
final class Acme_SN_Plugin {
    private static ?Acme_SN_Plugin $instance = null;

    public static function instance(): Acme_SN_Plugin {
        return self::$instance ??= new self();
    }

    public function init(): void {
        add_action( 'woocommerce_single_product_summary', [ $this, 'render_note' ], 25 );
    }

    public function render_note(): void {
        global $product;

        if ( ! $product instanceof WC_Product || ! $product->is_purchasable() ) {
            return;
        }

        $days = (int) apply_filters( 'acme_sn_handling_days', 2, $product );

        printf(
            '<p class="acme-sn-note">%s</p>',
            esc_html( sprintf(
                /* translators: %d: number of business days */
                _n( 'Ships in %d business day.', 'Ships in %d business days.', $days, 'acme-shipping-note' ),
                $days
            ) )
        );
    }
}

Priority 25 places the note after the short description (priority 20) and before the add-to-cart button (30). The next lesson, The WooCommerce Hook Map, lists these priorities. Also note three habits that you will repeat in every extension:

  • Check the type of what you receive ($product instanceof WC_Product) instead of trusting a global.
  • Escape at output (esc_html), and make text translatable.
  • Offer your own filter (acme_sn_handling_days) so other developers can adjust behavior without editing your plugin.

One caveat: block-based product templates do not necessarily run woocommerce_single_product_summary. If you target stores that use a block theme, test on one, and consider a block or a render filter for the same output.

Load order, visualized

sequenceDiagram
    participant WP as WordPress
    participant WC as WooCommerce
    participant X as Your plugin
    WP->>WC: include main file
    WP->>X: include main file (register hooks)
    WP->>X: plugins_loaded: acme_sn_boot checks class_exists
    WP->>X: before_woocommerce_init (early)
    X->>WC: declare_compatibility
    WP->>X: later hooks: features run

Top-level code only registers hooks; the real work happens after WooCommerce is known to be present.

Runnable stand-in: the bootstrap guard

The first stand-in models a plugin loader. A plugin declares what it requires; the loader decides whether to boot it and reports why not. The version comparison uses PHP's real version_compare, the same function the real guard uses.

PHP A bootstrap guard with requirements

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 real check is shorter because WordPress supplies class_exists and WC_VERSION, but the decision table is identical: boot, show a notice, or stay silent.

Runnable stand-in: why the hook timing matters

The second stand-in replays the startup events in order. A tiny event bus records when each callback runs and shows that a compatibility declaration registered too late is never seen.

PHP Startup events and a late declaration

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 demo uses a simplified order of three events so the point is easy to see. A real request fires many more hooks, but the rule holds: anything that must be known early belongs at the top level of your main file, and anything that needs WooCommerce classes belongs after plugins_loaded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the WooCommerce availability check run on plugins_loaded?

    At the top level of your file, WooCommerce may not be included yet. On plugins_loaded every active plugin has been included, so class_exists gives a reliable result.
  2. 2. What does Requires Plugins: woocommerce in the plugin header do?

    The header is enforced in the admin activation flow of WordPress 6.5 and later. Other activation paths exist, so a runtime guard is still needed.
  3. 3. Where must the custom_order_tables compatibility declaration be registered?

    The hook fires early, before WooCommerce sets up its features. Register the callback at load time; a callback added after the hook has fired never runs.
  4. 4. What should your guard do when WooCommerce is missing?

    A class that extends WC_Payment_Gateway is a fatal error when the parent is absent. Bailing out early and explaining why keeps the site working.

Summary

  • Add Requires Plugins: woocommerce and WC requires/tested up to headers, but still check at runtime.
  • Boot on plugins_loaded after confirming class_exists( 'WooCommerce' ) and a minimum WC_VERSION; load WooCommerce-dependent classes only after the check passes.
  • Declare HPOS and blocks compatibility on before_woocommerce_init, and only when your code really is compatible.
  • Hook small, typed, escaped features, and expose your own filters.
  • Stand-ins in this lesson model the guard and the event order; the WordPress code is read-only.

Next: The WooCommerce Hook Map