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 :
Awesome tool! I have it implemented on a plugin, and I’m noticed one small bug in WordPress 4.4 where the update seems to hang (even though it’s complete)… The update circle keeps spinning, and never shows the green check mark and “Updated!” Have you run into that before?
I have, but usually that only happens if the update fails for some reason. I just tested it on a WP 4.4 site and it worked fine.
Could you check your PHP error log? Maybe there was a warning or notice that messed up the AJAX response.
Yeah, I’m seeing no errors at all from it, with wp_debug enabled and an empty PHP error log (ironically using another of your plugins – you’re the man). Any other ideas as to how to trouble shoot it?
Ah, I’m seeing a JavaScript error on the page… any ideas?:
Uncaught TypeError: Cannot read property ‘replace’ of undefined
b.updates.updateSuccess @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:18
j @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:2
k.fireWith @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:2
(anonymous function) @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:16
j @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:2
k.fireWith @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:2
x @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:5
b @ load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils,underscore,wp-util,wp-a11y,updates,plu…:5
I’d look at the AJAX request with something like Firefox dev tools. Check what the server response is – presumably, it’ll be wrong in some way. Then try to trace PHP execution to see where exactly WP generates that response.
Oh, and one more thing: try using the version from GitHub. It has a few recent patches.
Found it! Had the wrong slug name listed in PucFactory::buildUpdateChecker()… Changed it, and it worked like a charm. Thank you so much for your work on this. What an incredible asset you are to the community.
I’m trying to use this on my localhost, so in my info.json I’ve got something like download_url: http://localhost/plugin.zip, but that doesn’t seem to work. Do you have any idea why?
What specifically is the problem? Which step doesn’t work – checking for updates, viewing update information, or update download/installation? Is there an error message?
https://github.com/YahnisElsts/wp-update-server/issues/33
Hi,
I tried your code as embedded in my Plugin (not using your code as external plugin). The code seems to work well as I see “1 plugin update available”. But when I go to Plugins list page, I don’t see any update available or when I go to the Updates page, I don’t see any updates available.
I am trying to use your code in Multi-Site environment. The Plugin which uses your update checker code is activated on one of the “Site”, it’s not Network Activated.
Please guide me what’s going wrong and how can I fix this issue.
Cheers,
Ruturaaj.
In Multisite, your plugin must be active on the main site for updates to work properly. This is because only those plugins will be running in the network admin. If your plugin isn’t running in the network admin, the update checker also isn’t running (because it’s part of your plugin), so it can’t show updates.
Thanks so much for your quick reply… I followed your instructions and it’s working good. 🙂
Thanks for sharing an awesome tool and your knowledge of wordpress.
My plugin is accessing the metadata.json file correctly and identifying that an update is available, but it is not performing the update. On the plugin page, the update spinner spins endlessly. If I load the details page in a new tab and attempt the update it gives me this message: Download failed. A valid URL was not provided.
I have the .zip archive in the same directory as the metadata file and they both require a secure connection. I can access the archive directly using the path wordpress claims in invalid.
Ever seen anything like this before?
Thanks!
Try the master branch from GitHub if you’re not already using it. It has a couple of recent compatibility improvements.
Are you running any other plugins on that site (especially anything security-related)? As you might already know, plugins and themes can hook into the WP HTTP API and change how WordPress validates URLs. I’ve seen a couple of cases where that has caused problems, especially when the .zip archive happens to be on the same host as the test site itself.
I updated to the latest code and I deactivated all of the other plugins on the site, but was still getting the invalid URL message.
After looking deeper into the comments here I found this article: http://www.emanueletessore.com/wordpress-download-failed-valid-url-provided/
After implementing that I still had no luck.
Since the update file was being hosted on the same domain (different subdomain) as the wp install, I tried moving it to a different domain all together and it worked! So, the issue must still be with wp not liking the same domain or the repo not allowing loopbacks, which given the above fix seems more likely. I’ll report back if I figure it out.
Thanks for your help.
Interesting. In theory, the latest code should fix “same domain” problem. It uses a workaround similar to the one in the article you mentioned. Let me know if you find a better solution.
I still haven’t been able to track down the issue, but am thinking that I have been looking in the wrong place… do you know what protocol and port wordpress uses to attempt the retrieval of the update archive? I am thinking it may be a firewall issue.
Usually it just sends a normal HTTP request. That’s either port 80 (plain HTTP) or port 443 (HTTPS).
Awesome tool. But I need to know a little more things.
1. I don’t want to create json file. Instead of json file I’ve done something which can return json response. How to use that with your solution ?
2. Secondly I don’t want to provide auto update. I just need to show the user that update is available. The user should download the update from my site. So how to remove the update link ? or it would be better if the update link redirect to my site ?
See my reply to the GitHub issue that you created.