Database “Migration” for Plugins?

I’m creating a plugin for WordPress. This plugin will need to save data to the database. In other programming frameworks I’ve worked with, there are systems called “database migrations”. These migrations are

  • SQL ALTER TABLE or CREATE TABLE statements/scripts
  • Sometimes abstracted into the programming language of the framework
  • Written and stored in a common way such that a user of my plugin/extension/etc can say “run the migrations” and the database will be update, per my instructions
    • And sometimes includes features that allow you to “rollback” those changes

An example migration system is Laravel’s.

Does WordPress have a system that’s similar to migrations? If not, is there a canonical way (via a particular hook, plugin registration, etc) to package up the new database tables and/or changes to existing WordPress tables my plugin will need?

1 Answer
1

Surprisingly not. Instead, you need to use the following function which is run whenever the plugin is activated.

define( 'YOUR_PLUGIN_VERSION', '1.0.0' );

register_activation_hook( __FILE__, 'your_plugin_activation_function' );

function your_plugin_activation_function() {
  // Do activation tasks here.
  your_install_function();
  your_upgrade_migration_function();
}

Run your install script.

function your_install_function() {

  // Set the current version of the plugin in the db.
  update_option( 'your_plugin_version', YOUR_PLUGIN_VERSION );
}

Then for each new version, you do a compare which basically performs your database migrations, etc.

function your_upgrade_migration_function() {

  // Using a version prior to 1.1.1
  if ( version_compare( YOUR_PLUGIN_VERSION, '1.1.1', '<' ) ) {
    // Do upgrade things unique for this version.
  }

  // Using a version prior to 1.2.0
  if ( version_compare( YOUR_PLUGIN_VERSION, '1.2.0', '<' ) ) {
    // Do upgrade things unique for this version.
  }
}

Leave a Comment