WordPress makes it easy to run scripts when a user activates or uninstalls your plugin, but what about when they update your plugin?
This script will look at your current plugin version and compare it to a saved version. If your plugin version is newer it will run an upgrade script based on the new version it sees and, finally, it will save the current plugin version to the WordPress database for later.
|
|
There are a few keys to this. First, on line 17, we call our updater in WordPress’ plugins_loaded hook.
It first requests a saved plugin version number from the database and compares it to the current version in the plugin header on line 10 if the current version is newer than the saved version it will then look at the $update_versions array.
This array contains the version to check and the function to run. In this case, if we change the plugin version to 1.0.1 it will run the update_1_0_1 function. We can add to this array for each new version and it will run the updates in the order listed. Note it doesn’t matter what new version you put here, it only matters that the actual new plugin version either matches the array version or exceeds it. I find this handy when I write an upgrade routine but my team hasn’t decided what the new version will be. As long as I increment the patch level by one it will work just fine.
One thing to note here is the default version, 0.0.0. This allows the upgrade routine to even run on new installs, which may or may not be what you want. I wrote this for a plugin where we want this behavior currently but, in the future, it would be trivial to modify the script to prevent it from running on the new installs. Simply change the default option on line 25 from 0.0.0 to false and check accordingly on line 29.
This simple routine will make running WordPress updates easy as you move forward with your WordPress plugin allowing you to easily enable new functionality such as changing database tables or more.