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 :

An upgrade notice for a privately hosted plugin.

An upgrade notice for a privately hosted plugin.

The version information window with placeholder data

The version information window with placeholder data

Download

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 :

496 Responses to “Automatic Updates For Private And Commercial Plugins”

  1. Ovidiu says:

    I can’t believe this, just 3 days ago I posted a possibly related question o nhte wp forums: why isn’t automatic upgrade enabled for plugins located inside mu-plugins? See the whole thread here: http://wordpress.org/support/topic/can-we-have-update-notifications-for-plugins-inside-the-mu-plugins-folder

    So here is a challenge for you or anyone interested: can your plugin be used to automatically upgrade plugins inside the mu-plugins folder?

  2. White Shadow says:

    I haven’t tried that, but probably not.

    This is because my library is not a full-blown automatic upgrade system. It is only a mediator. To put it simply, the custom update checker detects available updates and informs WordPress about them. Everything else – update notifications, user interface, actually installing the update – is left up to the built-in plugin upgrader. And since the built-in upgrader doesn’t know how to update plugins installed in the “mu-plugins” directory, you’re out of luck.

  3. White Shadow says:

    That reminds me – you might want to check out this old plugin of mine which is, in fact, a full-blown plugin upgrade system. It’s horribly outdated by now, but you could use it as a basis for something better.

  4. Jeff Rose says:

    Thanks for developing and sharing this. I’ve seen some mid-level tutorials that leave you to sort it out, and I haven’t had the time.

    Your full solution is exactly what I was looking for!

  5. Thanks from me, as well! I had *just* gathered enough information to start implementing private upgrades on my own, but I was going to be starting pretty much from scratch. This will save me (and many others) a lot of time and duplicated effort! (I did plan to share my work when I was done, though.)

  6. Ozh says:

    I don’t get why it’s so complicated?

    Hook into action ‘set_site_transient_update_plugins’ (as you do) a function that will check remote private API (much like what wp_update_plugins() does but with your own URL instead of api.wp.org) and if there’s a response, inject that response into the transient ‘response’ entry, again as you do

    No need for all the other stuff from your class like cron etc..? Or am I missing something?

  7. White Shadow says:

    Hmm, I must admit I simply didn’t think of that. You’d lose some configurability, but the code would indeed be simpler. The only problem I can see is that the filter would be called twice per a wp_update_plugins() call (edit: adding a simple flag to the main class would mostly solve this).

  8. Ozh says:

    Yeah indeed.

    A simple workaround would be not to hook into action ‘set_site_transient_update_plugins’ immediately but first add a filter on ‘http_request_args’ to check if this is a request to update plugins. Something like:

    add_filter(‘http_request_args’, ‘bleh_check_if_plugin’, 10, 2);
    function bleh_ckech_if_plugin( $r, $url ) {
    if ($url == ‘http://api.wordpress.org/plugins/update-check/1.0/’)
    add_action(‘set_site_transient_update_plugins’, ‘the_real_function’);

    return $r;
    }

    this way only the second set_site_transient( ‘update_plugins’ ) will trigger the private check

  9. White Shadow says:

    There’s a more significant problem that I just noticed: if multiple plugins call their own APIs in the ‘set_site_transient_update_plugins’ hook, any problem in one of the plugins can prevent all other plugins in the hook chain from running. For example, if one of the APIs is particularly slow, the whole thing could easily run over the PHP execution limit.

  10. […] need a way to parse a plugin’s readme.txt, or want to simplify metadata generation for the custom update checker, here’s a couple of utility functions that may come in handy. I originally wrote them for […]

  11. TJ says:

    Yeah, I have just tried to implement this. It doesnt seem to be working. Even when using the update check function. Does it work with WP 3.0.1?

  12. White Shadow says:

    Yes, it should work with 3.0.1. Any idea where it fails?

  13. TJ says:

    Not a clue, Or even what has to be different to cause an update, the zip file name or the metadata file version?

  14. White Shadow says:

    The “version” value in the metadata file has to be greater than the currently installed version of the plugin.

  15. TJ says:

    Yeah, see I’ve done that but still no go for me.

  16. White Shadow says:

    Try manually calling the requestInfo()/requestUpdate() methods of PluginUpdateChecker and var_dump the return values. Maybe that will provide some clues.

  17. TJ says:

    Both methods return NULL.

  18. TJ says:

    Actually, I’m Wrong, when I try to run any of them I get a fatal error in your script,

    Fatal error: Call to undefined function get_plugins() in —\——–\——–\—\plugin-updates\plugin-update-checker.php on line 167

  19. White Shadow says:

    This means that the class either can’t download the metadata file, or can’t parse it due to syntax errors in the file. You can test the first possibility by trying to fetch the file with wp_remote_get(). As for JSON syntax, run the file through one of the many online JSON validators.

  20. White Shadow says:

    Oh, in that case you can disregard the above comment.

    That error was a known issue in the first release. Re-download the client library and try again, it should work.

Leave a Reply