Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Quality and Production

Compatibility, Upgrades and Distribution

Ship a WooCommerce extension safely: version checks, deprecations, database migration routines, compatibility declarations, translations, packaging and a release checklist.

Writing the plugin is half the job. The other half starts when real stores run it: WooCommerce releases new versions several times a year, your own plugin needs new database columns, old hooks have to be retired politely, and somebody has to turn a folder of code into a zip file that installs cleanly. This lesson covers the habits that keep an extension working across versions and make updates boring, which is exactly what store owners want.

The real mechanisms (plugin headers, FeaturesUtil, wc_deprecated_function(), dbDelta()) need WordPress, so they are shown read-only. The runnable parts are stand-ins: a version-gate helper and a small migration runner over SQLite that behaves like the upgrade routine you will write in your plugin.

Declare what you support

WooCommerce reads a few extra lines from your plugin header. They are metadata for the admin screens and the status report, not a runtime guard:

PHP
<?php
/**
 * Plugin Name:       Acme Bulk Discounts
 * Version:           1.4.0
 * Requires at least: 6.5
 * Requires PHP:      8.1
 * Requires Plugins:  woocommerce
 * WC requires at least: 9.0
 * WC tested up to:      10.2
 * Text Domain:       acme-bulk
 * Domain Path:       /languages
 */
  • Requires Plugins: woocommerce makes WordPress (6.5 and newer) refuse to activate your plugin while WooCommerce is missing. Older WordPress versions ignore it, so keep a runtime check too (see Your First WooCommerce Extension).
  • WC requires at least and WC tested up to tell shop owners and the status report which versions you have really tested. Update tested up to only after you ran your tests against that release.
  • Be honest in Requires PHP. Raise it deliberately in a minor or major release and write it in the changelog.

Feature compatibility declarations

WooCommerce lets extensions state which optional platform features they support. The two you must handle are High-Performance Order Storage (HPOS, see Orders and High-Performance Order Storage) and the cart and checkout blocks:

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
        );
    }
} );

Only pass true when it is true. Declaring HPOS compatibility while your code still calls get_post_meta() on orders is a lie that corrupts data on stores with HPOS enabled. Declare false for a feature you know you do not support; the admin then warns the owner before they enable it.

Version checks without fragility

Prefer feature detection over version numbers: function_exists( 'wc_get_order' ), class_exists( ... ). When you really need a version (for instance to use a newer API when available), compare with version_compare() against WC_VERSION, and handle missing constants:

PHP
<?php
function acme_wc_at_least( string $version ): bool {
    return defined( 'WC_VERSION' ) && version_compare( WC_VERSION, $version, '>=' );
}

Two traps: version strings such as 9.4.0-beta.1 sort before 9.4.0, so a beta of the release you need does not count; and never compare with == or as plain floats (9.10 is a smaller float than 9.9). version_compare() understands dotted versions properly.

Retiring your own hooks and functions

Your plugin is an API too: other developers hook into your actions and call your helpers. When you rename or remove something, keep the old name working for a few releases and log a notice. WooCommerce provides helpers that only print notices when WP_DEBUG is on and log through the standard deprecation machinery:

PHP
<?php
function acme_get_tier_price( $product_id, $qty ) {
    wc_deprecated_function( __FUNCTION__, '1.4.0', 'Acme_Pricing::price_for' );
    return Acme_Pricing::price_for( (int) $product_id, (int) $qty );
}

// Old filter name still fires, with a warning, next to the new one.
$price = apply_filters( 'acme_bulk_price', $price, $product );
$price = apply_filters_deprecated( 'acme_bulk_discount_price', [ $price, $product ], '1.4.0', 'acme_bulk_price' );

wc_deprecated_function(), wc_deprecated_hook() and wc_deprecated_argument() are WooCommerce's versions, and WordPress has the generic _deprecated_function() and apply_filters_deprecated() family. The rule of thumb: announce in the changelog, warn in debug mode for at least a couple of minor versions, remove only in a major version. Deprecation warnings never appear to shoppers on production because notices are hidden unless debugging is enabled.

Database versions and migrations

When version 1.4 of your plugin needs a new table or a changed option format, you cannot rely on the activation hook alone: plugins are usually updated by replacing files, and activation does not run again. The standard pattern stores a schema version and compares it at load time:

flowchart TD
    A["Request starts<br/>(init or admin_init)"] --> B{"Stored db_version<br/>= code version?"}
    B -- yes --> Z["Nothing to do"]
    B -- no --> C["Take a lock"]
    C --> D["Run each migration<br/>newer than stored version"]
    D --> E["Save new db_version<br/>after each step"]
    E --> F["Release lock"]

Migrations run in order, save progress after each step, and are safe to repeat.

PHP
<?php
const ACME_DB_VERSION = '1.4.0';

add_action( 'init', function () {
    $stored = get_option( 'acme_db_version', '0' );
    if ( version_compare( $stored, ACME_DB_VERSION, '>=' ) ) {
        return;
    }
    if ( get_transient( 'acme_migrating' ) ) {
        return;                                    // another request is already on it
    }
    set_transient( 'acme_migrating', 1, 5 * MINUTE_IN_SECONDS );

    if ( version_compare( $stored, '1.2.0', '<' ) ) {
        acme_migrate_1_2_0();                     // create table with dbDelta()
        update_option( 'acme_db_version', '1.2.0' );
    }
    if ( version_compare( $stored, '1.4.0', '<' ) ) {
        acme_migrate_1_4_0();                     // rename meta key in batches
        update_option( 'acme_db_version', '1.4.0' );
    }
    delete_transient( 'acme_migrating' );
} );

Rules for good migrations:

  • Idempotent. Running a step twice must not break anything. dbDelta() already behaves this way for tables; for data steps check before you change.
  • Small and resumable. On a store with 500,000 orders, a single request will time out. Do heavy work in batches through Action Scheduler and keep the stored version at the last finished step.
  • Never edit an old migration that has shipped. Add a new one.
  • Use CRUD or $wpdb->prepare(), never string-built SQL (see Security for WooCommerce Extensions).
  • Keep the activation hook thin. Call the same upgrade function from activation and from the version check so fresh installs and upgraded installs end in the same state.

Translations

Wrap every visible string in __( 'text', 'acme-bulk' ) or esc_html__(). Use one text domain that matches your plugin slug, and avoid building sentences from pieces, because other languages reorder words. Use placeholders with sprintf() and translator comments:

PHP
<?php
/* translators: %d: minimum quantity for the tier */
$label = sprintf( __( 'Buy %d or more', 'acme-bulk' ), $min_qty );

Plugins hosted on WordPress.org get translations loaded automatically; for others, call load_plugin_textdomain() on init. Generate the template file with wp i18n make-pot . languages/acme-bulk.pot, and use _n() for plurals, since some languages have more than two plural forms. Prices must always go through wc_price() rather than manual symbol concatenation, so currency position and separators follow the store's settings (see Taxes, Currency and Formatting).

Packaging and release

A release is a zip whose top folder has the plugin slug. Keep development files out of it:

TEXT
acme-bulk/
  acme-bulk.php
  readme.txt
  includes/
  assets/
  languages/
  templates/
  uninstall.php

A .distignore (or your build script) excludes tests/, node_modules/, .github/, composer.json dev dependencies, and source maps you do not want to ship. Ship built assets, not the build tools. The readme.txt carries the short description, the stable tag, the tested-up-to values and the changelog.

If you plan to sell through a marketplace, read its current submission guidelines before you start, because requirements change over time: they generally cover code quality checks, security review, licensing, compatibility declarations and support expectations. Do not assume details; check the official documentation for the requirements of the day.

A release checklist

  1. All tests pass on the oldest and newest supported PHP and WooCommerce versions (see Testing WooCommerce Code).
  2. Version number bumped in the header, the constant, readme.txt and the changelog.
  3. WC tested up to updated only after a manual run through the cart, checkout and an order edit with HPOS on and off.
  4. Migrations tested from the oldest version you support, not only from the previous one.
  5. Translation template regenerated; no debug output or var_dump() left behind.
  6. Zip built from a clean checkout, installed on a fresh site, activated, and removed again to test uninstall.php.
  7. Tag created, release notes written, and a rollback plan ready (the previous zip).

Runnable stand-in: a migration runner

This is not WordPress: get_option() becomes an SQLite table, and migrations are PHP closures instead of dbDelta() calls. What it shares with the real thing is the structure: ordered steps, a stored version saved after every step, and safe re-runs.

PHP Migration runner with stored version

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.

A real plugin would add a lock (the transient above), batch big data steps and use dbDelta() for DDL. The key behaviour is visible: the second run does nothing, and an update only runs the new step.

A second stand-in covers version gates and one-time deprecation notices:

PHP Version gates and deprecation notices

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 your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a plugin compare a stored schema version at load time instead of relying only on the activation hook?

    Updates normally overwrite the plugin folder, so activation does not run. A stored version checked on load notices that the code is newer than the database and runs the missing migrations.
  2. 2. Which statement about declaring HPOS compatibility is correct?

    The declaration is a promise. A false promise lets the store enable HPOS while your code reads and writes the wrong tables.
  3. 3. What makes a migration step safe to run more than once?

    Requests can overlap and steps can be interrupted. Idempotent steps plus a version saved after each one let the runner resume without damage.
  4. 4. How should you retire a public function or hook of your plugin?

    Other plugins and themes depend on your API. A deprecation period with debug-only notices gives them time to switch.
  5. 5. Why is comparing version numbers as floats a bug?

    Dotted versions are sequences of integers, not decimals. Use version_compare(), which understands them, including pre-release suffixes.

Summary

  • Header fields document your requirements; runtime checks and feature detection enforce them.
  • Declare HPOS and blocks compatibility honestly with FeaturesUtil::declare_compatibility().
  • Use version_compare(), never floats or string equality.
  • Deprecate before you remove, with wc_deprecated_function() and apply_filters_deprecated().
  • Store a DB version, run ordered, idempotent migrations, and batch heavy work with Action Scheduler.
  • Translate every string with one text domain, package a clean zip, and follow a written release checklist.

Next: Project: Bulk Discount Extension