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?


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.

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.
| improve this answer | |
  • Useful, thank you. What about something like dbDelta -- is that OK to trust/use in place for version compares? developer.wordpress.org/reference/functions/dbdelta – Alan Storm Sep 24 '16 at 2:30
  • @AlanStorm Yes - If you're creating/modifying a db table, dbDelta is what you need. codex.wordpress.org/… Ideally though, you leverage the existing WordPress schema and caching layer by storing any plugin data in the wp_options table. – cowgill Sep 24 '16 at 2:43
  • 1
    +1'd for your answer, thank you. I'm leaving this open for a bit -- still hoping for something more complete (this answer missed dbDelta, curious if there's other functions/systems to help with migration like tasks) – Alan Storm Sep 24 '16 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.