DevinVinson / WordPress-Plugin-Boilerplate

[WordPress] A foundation for WordPress Plugin Development that aims to provide a clear and consistent guide for building your plugins.
http://wppb.io
7.66k stars 2.25k forks source link

How to handle plugin updating? #523

Open netpalantir opened 4 years ago

netpalantir commented 4 years ago

Hi, my plugin based on WPPB is working, but I need to make some updates that require a database migration. How can I handle this?

I can see the version definition in the main php file:

define( 'XXXX_VERSION', '1.0.0' );

Once I have updated this to, say, 2.0.0, how can I detect that the plugin is outdated, and perform some actions?

I mean: is there already some boilerplate for this?

Defkon1 commented 4 years ago

same question... I need to update database, too...

Defkon1 commented 4 years ago

Ok, figured out by myself:

  1. update plugin version in the main <your-plugin-name>.php ("Plugin bootstrap file" section)
  2. update plugin version in the define( 'XXX_VERSION', 'x.x.x') declaration (same file)
  3. modifiy the CREATE TABLE commands in the init_db()method in the class-pluginname-activator.php, the dbDelta() function will do the magic (creating or altering the tables where required)
netpalantir commented 4 years ago

My final code is like this:

define( 'XXX_VERSION', '2' );

// ...

$cdpVersion = get_option('xxx_version');
if(!$cdpVersion) {
  $cdpVersion = '1';
}
if($cdpVersion !== XXX_VERSION) {
  update_option('xxx_version', XXX_VERSION);

  require_once plugin_dir_path( __FILE__ ) . 'includes/class-xxx-activator.php';
  Xxx_Activator::activate();
  Xxx_Activator::migrate($cdpVersion, XXX_VERSION);
}

This will first call the activate() function, that uses dbDelta() to perform all the required changes.

However, I also needed to perform some inserts and updates which dbDelta won't do. For this I created a migrate function, function on the Activator, which accepts the current version as the first parameter, and the required version, so I can do all the necessary changes.

Hope this helps.

adamradocz commented 4 years ago

I added an Updater class to my fork. Check it out if you want.