Automatic Updates For Private And Commercial Plugins
Last updated on June 26, 2015.
Since time immemorial, only plugins hosted in the official WordPress.org plugin directory have supported automatic updates. Now, I’ve written a PHP library that you can use to add automatic update capabilities to any plugin. Public, private and commercial plugins alike – all can now enjoy the benefits of automatic update notifications and one-click upgrades.
The custom update checker integrates closely with the upgrade system already built into WordPress, producing a seamless user experience. Observe :
Download
- Client library (requires WP 3.2 or later)
- Example plugin
- Example metadata file
- GitHub repository
License
This library is released under the MIT License and is distributed free of charge. If you find it useful, consider making a donation.
Quick-start Guide
This section describes the quickest way to get automatic updates working for your plugin. Here’s what you’ll need to do: create a metadata file for your plugin, host it somewhere publicly accessible, and tell the update checker where to find it.
Lets start with the metadata. Copy the JSON code below into a new file and replace the placeholder values with your plugin’s info.
{ "name" : "My Cool Plugin", "slug" : "my-cool-plugin", "download_url" : "https://example.com/plugins/my-cool-plugin.zip", "version" : "2.0", "author" : "John Smith", "sections" : { "description" : "Plugin description here. Basic HTML allowed." } }
(This is the minimum amount of data required to make automatic updates work. In most cases, you will probably want to add a couple more fields. See the metadata docs for a full list.)
Most of the fields should be pretty self-explanatory, with one possible exception – the “slug”. WordPress expects all plugins that support automatic updates to have a unique textual identifier called the “slug”. Normally, slugs are assigned by the official plugin directory. For a private/commercial plugin that’s hosted elsewhere you’ll have to make something up. If unsure, just use the plugin’s file name without the “.php” extension (my-cool-plugin/my-cool-plugin.php becomes my-cool-plugin).
Upload the metadata file you just created to your web server. It doesn’t matter where exactly you put the file or how you name it. The important thing is for its URL to be accessible from wherever someone might install your plugin.
Next, copy the “plugin-update-checker” directory from the client library archive to your plugin’s directory. Then fire up your favourite code editor and add the following lines to the top of your plugin file:
require 'plugin-update-checker/plugin-update-checker.php'; $MyUpdateChecker = PucFactory::buildUpdateChecker( 'https://example.com/path/to/metadata.json', __FILE__, 'your-chosen-slug' );
If you followed my advice and used the plugin’s file name as the slug, you can omit the third parameter of the PucFactory::buildUpdateChecker()
call.
Tip: Sometimes you’ll run into a situation where another active plugin is also using this update checker. As a result, there could be several different versions of the library loaded at the same time. The above code snippet will always give you the latest available version. This can be a problem if your plugin expects an older version and is not API-compatible with the latest version.
To use a specific version of the update checker (e.g. the one included with your plugin), instantiate the PluginUpdateChecker_x_y
class directly. Replace x
and y
with the major and minor version numbers:
//Use version 2.0 of the update checker. require 'plugin-update-checker/plugin-update-checker.php'; $MyUpdateChecker = new PluginUpdateChecker_2_0 ( 'https://example.com/path/to/metadata.json', __FILE__, 'your-chosen-slug' );
And that, believe it or not, is it.
The PluginUpdateChecker class will handle the rest. It’ll check the metadata file every 12 hours and, if it discovers that a new version has been released, twiddle the right bits in the undocumented WP API to make it show up as a standard upgrade notification in the “Plugins” tab. Assuming you’ve provided a valid download_url
, users will be able to install the update with a single click.
Tip: When creating the ZIP file for an update, put all plugin files inside a directory. The directory name should match the plugin slug. Do not put the files at the root of the ZIP archive – it can cause subtle bugs and errors when someone ties to install the update.
The rest of this post will be devoted to a more in-depth discussion of the update checker class and the metadata format.
The PluginUpdateChecker class
This class is the core of the update checker. It’s also the only part of the updater that you should need to deal with unless you decide to extend the library yourself.
Class constructor
All configuration settings should be specified by passing them to the PucFactory::buildUpdateChecker() factory method, or directly to the PluginUpdateChecker constructor. Both takes the following parameters:
$metadataUrl
– The full URL of the plugin’s metadata file.$pluginFile
– The path to the plugin’s file. In most cases you can simply use the __FILE__ constant here.$slug
– The plugin’s ‘slug’. If not specified, the filename part of $pluginFile (sans “.php”) will be used as the slug.$checkPeriod
– How often to check for updates (in hours). Defaults to checking every 12 hours. Set to zero to disable automatic update checks.$optionName
– Where to store book-keeping info about updates. Defaults to “external_updates-$slug”.
checkForUpdates()
Manually trigger an update check. This is especially useful when you’ve disabled automatic checks by setting $checkPeriod (above) to zero. This method takes no parameters and returns nothing.
addQueryArgFilter($callback)
Register a callback for filtering query arguments. Whenever the update checker needs to retrieve the metadata file, it will first run each filter callback and attach the query arguments that they return to the metadata URL. This lets you pass arbitrary data to the server hosting the metadata. For example, commercial plugins could use it to implement some kind of authorization scheme where only users that have the right “key” get automatic updates.
The callback function will be passed an associative array of query arguments and should return a modified array. By default, the update checker will add these arguments to the metadata URL:
installed_version
– set to the currently installed version of the plugin.checking_for_updates
– set to 1 if checking for updates, absent otherwise (i.e. when loading data for the “Plugin Information” box).
This method takes one parameter – the callback function.
addHttpRequestArgFilter($callback)
Register a callback for filtering the various options passed to the built-in helper function wp_remote_get that the update checker uses to periodically download plugin metadata. The callback function should take one argument – an associative array of arguments – and return a modified array or arguments. See the WP documentation on wp_remote_get for details about what arguments are available and how they work.
This method takes one parameter – the callback function.
addResultFilter($callback)
Register a callback for filtering plugin info retrieved from the metadata URL.
The callback function should take two arguments. If the metadata was retrieved successfully, the first argument passed will be an instance of PluginInfo (see the source for a description of this class). Otherwise, it will be NULL. The second argument will be the corresponding return value of wp_remote_get (see WP docs for details). The callback function should return a new or modified instance of PluginInfo or NULL.
This method takes one parameter – the callback function.
Metadata format
The automatic update system uses a JSON-based file format to describe plugins. Essentially, the entire file is one big JSON-encoded object (AKA hash-table or associative array). Each field – or array key – represents a piece of information about the latest version of the plugin. The full description of all available fields is here.
For the sake of simplicity, both general metadata and update-related information are stored in the same file. If this is undesirable, you can replace the plain JSON file with a script that checks for the presence of the the “checking_for_updates” query parameter and emits just the update-related fields if its set to “1”.
Notes
Your plugin must be active for updates to work. The update checker is just another piece of PHP code loaded and run by your plugin, and it won’t be run if the plugin is inactive.
One consequence of this that may not be immediately obvious is that on a multisite installation updates will only show up if the plugin is active on the main site. This is because update notifications usually appear in the network admin, and only plugins active on the main site are loaded in that case. The main site of a WordPress network is the one that was created first and has the path “/” in the Sites -> All Sites list.
Related posts :
Yes, it seems to work fine in WP 3.5. I use it in one of my commercial plugins and haven’t noticed any problems with the latest release.
Cool – it must be something on my end then because I’m clearing out the transients manually and checking for updates and they’re not showing up. I’ll try to figure it out.
Thanks for putting this together.
Regards.
Take a look at the update checker’s Debug Bar panel – it outputs a bunch of debugging information there that might help you identify the problem.
Any reason why you don’t use regular `pre_set_site_transient_update_plugins`? Like here – https://github.com/jeremyclark13/automatic-theme-plugin-update/blob/master/plugin/test-plugin-update/test-plugin-update.php
Thank you for answer
There are several reasons why I don’t use that hook:
– It risks breaking other plugins. If I use that hook and my update checker crashes for any reason (script timeout, bug, whatever), it will prevent WordPress from recording update data for other plugins.
– I wanted to make the check interval configurable.
– I didn’t want to rely on undocumented behaviour. Right now, WordPress only modifies that transient when storing plugin updates, but there’s no guarantee that this will remain the case in future versions. Also, other plugins might decide to modify it (thus running the update hook) for their own reasons.
I have not tried yet… but could you tell me if this method will work correctly for my common functions plugin housed in /wp-content/mu-plugins?
Thanks in advance!
No, I’m pretty sure it wouldn’t work properly in that case. I tried it a while ago and while the library was able to retrieve update information and display the “Update (1)” bubble in the admin menu, the update itself didn’t actually show up and it wasn’t possible to install it.
Worked like a charm. Tried another one prior to this…couldn’t figure that one. This one was like piece of cake.
Thank you.
Hi,
I’ve installed this plugin on one of my public plugins and I also added code that sends URL of site (for statistics purpose).
I’ve got about 20 installations per day, and on 99% of sites it works correctly – update check request is sent every 24h.
But on about 1% of all installations “update check request” is being sent over and over (probably on each page reload). Do you have any idea what might cause this and how to prevent such issue?
Thank you for awesome work!
Well, there are two ways this library can trigger an automatic update check:
1) Periodic checks scheduled via WP Cron. I think we can safely assume that WordPress’ Cron implementation has been extensively tested and is unlikely to be the source of the problem.
2) Every time the user accesses an admin page, the library checks the database option that it uses to store the update data. If the stored data is missing or out of date (i.e. older than the configured update period), it will attempt to check for updates. Note that even if the update check fails, it will record the last check time and won’t try checking again until X hours have passed.
So, in theory, if something were to prevent the update checker from reading or modifying its DB option, it would check for updates on every admin page load. Unfortunately, I have no idea what could cause the DB read/write to fail. I’ve reviewed the relevant code and I can’t find anything wrong with it. Still, it might be something worth looking into if you can get the problem to manifest in a reproducible manner.
Like everyone else, I find your update checker incredibly useful and easy to use.
Have you seen any issues where someone has 2 plugins installed where both use your plugin checker and 1 is version 1.1 and the other is version 1.3, and the “Check for update” link doesn’t appear?
At least I think that’s what’s happening, any thoughts?
I figured it out. My fault. I hadn’t changed the class name on my side.
PluginUpdateChecker PluginUpdateChecker_1_3
To avoid problems like that, consider using the new factory class introduced in 1.3. It lets you automatically instantiate the newest available version of the update checker without having to worry about version numbers. The class is not properly documented yet, but basically you just replace “new PluginUpdateChecker(…)” with “PucFactory::buildUpdateChecker(…)”:
Thanks for that tip. I knew there had to be a better way.
Hi,
great post. Working great, except that after the update i am not able to edit the plugin files through any IDE (like Netbeans). Gives a message saying “Error saving file….”, but i am able to edit the plugin through the dashboard.
thanks in advance
I’m guessing you’re using Linux or another Unix-like system, and when you update the plugin it changes file ownership to the web server user, so you can no longer edit them from your own account. This is a server configuration issue and has nothing to do with the update checker as such.
Hi,
Thanks for the quick reply 🙂
I am using windows, but your right it should be a server config issue.
[…] 该方法同样来自于 w-shadow.com […]
This looks very useful, thank you.
Question: how could this be used to pass along an extra parameter? I had in mind, a licence key. As I read it, in the suggested setup, the plugin zip is public. Can this be achieved in the library’s present form, or does it need hacking?
You can use the
$updater->addQueryArgFilter($callback)
method to attach a filter that will add extra parameters to update requests. See the post itself for details.You will also need some kind of a server script that verifies those parameters – like your license key – and outputs the download URL only if they are valid. This library doesn’t include anything like that; you’ll need to write it yourself 🙂 Personally, I use a licensing library I wrote myself (alas, it’s not good enough to release publicly).