Writing an Upgrade Procedure for your Plugin

We all need to release updates to our plugins from time to time. Whether its to introduce new (or enhance existing) functionality,  fix bugs, or simply increment the supported WordPress version. Depending on the changes you are making to your plugin, there may be tasks that you need to execute as part of an upgrade procedure. These tasks can be anything Рadding new options, updating post meta keys, etc.

Let’s take a look at how we can achieve this within our plugin by hooking into the admin_init¬†WordPress hook.

A Basic Example

In this example, we’re simply using the upgrade procedure to increment the version of our plugin stored within the database, as well as record the version we’re upgrading from. I always find it useful to store the version we upgraded from as this can help when providing support.

This basic upgrade procedure would be sufficient for the majority of plugin update.

A Little More Advanced

OK so now we have the basics nailed and our upgrade procedure is running when required, we can add some additional code to perform a change that is needed for the newer version of our plugin.

In the example below, we’re simply checking the version being upgraded from and running additional upgrades as needed. In this case, we’ll add a new meta key and value to all posts currently in the ‘draft’ status.

Even More Advanced

Our basic example above is all well and good, but what if there were thousands of posts we needed to update? With an intensive upgrade procedure we need to take a slightly different approach to ensure that the server the upgrade is running on does not time out unexpectedly.

For KB Support, we address that by reverting to an Ajax based upgrade routine. It’s a little too much code to include here, but feel free to review directly in the KB Support GitHub Repo.

Leave a Reply