WordPress Development

Plugin Upgrade Routines: Changing Your Database Safely Between Versions

Plugin Upgrade Routines: Changing Your Database Safely Between Versions

At some point, every plugin outgrows its first data structure. A setting needs a new format. A custom table needs another column. Data stored in post meta needs to move into its own table for performance. On your development site, you make the change, update your code and everything works. Then the new version goes out, and support requests arrive from sites where the old data was never converted. Plugin upgrade routines exist to handle exactly this.

The usual cause is a misunderstanding about when code runs. Many developers put database setup in the activation hook, assuming it runs on updates. It doesn’t. When a plugin updates through the dashboard, WordPress replaces the files but doesn’t deactivate and reactivate the plugin. Your activation code never runs. Reliable plugin upgrade routines solve this by checking, on every load, whether the site’s data is at the version the code expects, and migrating it if not.

The core pattern: store a version

The foundation is simple. Store the version of your data structure in an option, and compare it with the version your code expects.

Use a separate data version rather than the plugin’s release version. Many releases don’t change data at all, and an integer schema version is simpler to compare than strings like 2.3.1.

The check itself is very cheap: one autoloaded option compared with a constant. It costs almost nothing on every request.

Running migrations in order

Each data change becomes a numbered step. The upgrade routine runs every step newer than the installed version, in order, and records progress after each one:

Recording the version after each step means that if step 3 fails, the next request starts at step 3 again rather than re-running steps 1 and 2. A fresh install starts at zero and runs every step, so new and upgraded sites end up with identical structures.

Creating and changing tables with dbDelta

For custom tables, WordPress provides dbDelta, which compares a CREATE TABLE statement with the existing table and adds missing columns and indexes:

dbDelta is famously strict about formatting. Each field must be on its own line, PRIMARY KEY needs two spaces before the opening parenthesis, and KEY must be used rather than INDEX. Small deviations cause it to silently skip changes. Copy the format exactly.

dbDelta adds columns and indexes but won’t drop columns, rename columns or change data. For those, use explicit ALTER TABLE statements in a migration step, after checking whether the change is still needed:

Checking before acting makes the step safe to run more than once, which matters if a previous attempt partly succeeded.

Migrating settings and data

Not every migration involves tables. Option formats change, meta keys get renamed, data moves from one place to another.

if ( ! is_array( $old )isset( $old['display'] ) ) {

Keep migrations idempotent wherever possible: running a step twice should be harmless. Check whether data is already in the new format before converting.

Large data migrations

Converting a few options is instant. Moving data for 200,000 posts is not. Running a huge migration during a single request leads to timeouts, half-migrated data and very unhappy site owners.

For large migrations:

  • Split the work into batches, each processing a few hundred records.
  • Run batches in the background, using Action Scheduler or a WP-Cron chain, rather than during a visitor’s request.
  • Track progress in an option, so the migration can resume after interruption.
  • Keep the old data readable until migration finishes, so the plugin works during the transition. Code may need to read from both old and new locations temporarily.
  • Show an admin notice with progress for large sites, so administrators know what’s happening.
  • Offer a WP-CLI command to run the migration directly on large sites, avoiding web timeouts entirely.

WooCommerce’s own database updates follow this pattern: after an update, it shows a notice, runs migrations in the background with Action Scheduler and reports when they’re complete.

Concurrency: two requests upgrading at once

On a busy site, the moment a new version goes live, several requests may arrive at once, each seeing an old version number and each starting the upgrade. Two processes altering the same table or migrating the same data simultaneously can cause errors or duplicated work.

A simple lock helps:

It isn’t a perfect lock, but it prevents the most common collisions. For critical migrations, use add_option, which fails if the option already exists, as an atomic lock.

Downgrades and rollbacks

Site owners sometimes roll back to an older plugin version after an update causes problems. If the new version changed data in ways the old version doesn’t understand, the rollback can break things further.

Design migrations with this in mind where you can:

  • Add new columns and options rather than removing old ones immediately.
  • Keep old data for a release or two before cleaning it up.
  • Document in your changelog when a version contains a data migration that can’t be reversed.

Multisite

On a multisite network, each site may have its own tables and options. A plugin network-activated on a large network might need to upgrade hundreds of sites. Running every site’s upgrade on the first request is impractical. Upgrade each site lazily when it’s first loaded after the update, or process sites in the background, and provide a WP-CLI command to upgrade all sites at once.

Testing upgrades

Most upgrade bugs are found by users because developers test fresh installs, not upgrades. Before releasing a version with a migration:

  1. Install the previous version on a test site and create realistic data.
  2. Update to the new version through the dashboard, not by copying files.
  3. Check that the data version advanced and data looks correct.
  4. Test an upgrade from several versions back, not just the previous one.
  5. Test on a site with a large dataset to see how long migrations take.

Reliable plugin upgrade routines are invisible when they work. That’s exactly the goal: users click “Update” and everything continues as if nothing changed underneath.

Communicating data changes to users

When a release contains a significant migration, tell users. A line in the changelog such as “This version moves event data to a new table; large sites may see a short background process after updating” sets expectations and reduces support requests. For major changes, consider a pre-update notice in the previous version, suggesting a backup before updating.

A checklist for each migration

Before shipping a release that changes data, run through a short list:

  • Is the schema version incremented, with a new numbered step?
  • Is the step safe to run twice?
  • Does it handle sites upgrading from several versions back?
  • Will it finish quickly on large sites, or does it need batching?
  • Does the plugin still work while a background migration is in progress?
  • Is there a WP-CLI command for large sites?
  • Has it been tested by updating through the dashboard on a site with realistic data?

Teams that follow a checklist like this rarely receive the dreaded “after updating, all my data disappeared” support ticket. Well-planned plugin upgrade routines turn database changes from a risky event into routine maintenance.

Uninstall is part of the lifecycle

The reverse of upgrades matters too. When someone deletes your plugin, uninstall.php should remove its options, custom tables and scheduled tasks, ideally after asking whether to keep data for a future reinstall. Clean uninstalls leave sites tidy and show users that your plugin respects their database.

Feature flags during transitions

For risky changes, ship the new code path behind a setting or filter that stays off until the migration completes. If something goes wrong, sites keep using the old path while you investigate. Once the new path is proven on many sites, remove the flag in a later release. This gradual approach is common in larger plugins and costs little to adopt in smaller ones.

Logging migration results

Record when each migration step ran and whether it succeeded, either in an option or a small log. When a user reports a problem weeks later, knowing that step three ran on a particular date, and how many records it processed, turns a guessing game into a quick diagnosis.

Keep migrations in the codebase

Don’t delete old migration steps once most users have upgraded. Someone will eventually update from a very old version, and the full chain of steps is what brings their data up to date safely.

Frequently asked questions

Why doesn’t register_activation_hook run on updates?

Because WordPress doesn’t deactivate and reactivate plugins during updates. It only replaces the files.

Where should the upgrade check run?

On plugins_loaded or init, early enough that the rest of the plugin uses the upgraded data, and on both front-end and admin requests.

Can I use the upgrader_process_complete hook instead?

It fires after updates through the WordPress updater, but not when files are replaced by deployment, FTP or Composer. A version check on load catches every case.

Should I delete old data after migrating?

Eventually, but not immediately. Keep it for at least one release so rollbacks remain possible.