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. Zach says:

    Sounds good, thanks!

  2. Zach says:

    Hi Janis,
    Was having some trouble integrating with my own plugin, so I used the example one you provided (updating the URL paths in both the plugin and the JSON file to valid files on my server) and am still getting the following error:

    An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.

    Anything you’ve come across on your end? Thanks!

  3. Jānis Elsts says:

    Most likely, there’s something wrong with the “plugins_api” filter. This filter lets plugins override the contents of the “Plugin Information” pop-up, and the update checker uses it to display the information from your metadata file. See PluginUpdateChecker::injectInfo() for the implementation.

    WordPress displays that particular error message when the “plugins_api” filter returns false and the plugin isn’t listed in the default WP plugin repository. So something is causing the filter to return false. I would recommend sprinkling some var_dump()’s throughout the injectInfo() method to see where it goes wrong 🙂

    Also, are you by any chance using one of WooThemes products on your site? Their custom update checker implementation has a nasty bug where it will overwrite any “plugins_api” filter value with false if the current request isn’t about one of their own plugins. You can work around this problem by changing the “plugins_api” filter priority in PluginUpdateChecker from 10 to, say, 20.

  4. Zach says:

    Hm, didn’t have any WooThemes stuff installed, but did have a few other plugins (Event Calendar Pro, RelevanSSI, and Gravity Forms) that were using that filter – so after using a higher priority – that fixed it! Any thoughts on if this’ll impact the others since we’re changing how this is loaded, or is this more “their” fault and it shouldn’t effect them? Thanks!

  5. Jānis Elsts says:

    The priority change shouldn’t affect other plugins. If this class detects that the current plugin information request is for a different plugin, it will just return the original value unmodified. It won’t overwrite the result.

  6. Zach says:

    Gotcha, thanks!

  7. […] Plugin Update Checker 1.2 Released After a long delay, a new version of my PluginUpdateChecker library is finally ready for release. Read on to find out what’s new, or go straight to the download page. […]

  8. djbokka says:

    I’ve used your plugin successfully in the past but when trying to implement now, I only get partial functionality.

    The update ticker works (little circle that says there are “3” updates available) but when I click on plugins none of them show as updatable or are able to be updated.

    Have you experienced anything like this before that may allow you to point me in the right direction?

    Many thanks, and thank you for your work on this.

  9. Jānis Elsts says:

    No, I don’t know what could cause that.

    Check the update checker’s Debug Bar panel – does the update show up there? It should say something like “an update is available” and display the update details at the bottom.

    (Of course, you’ll need to have the Debug Bar plugin installed to do the above.)

  10. Denis says:

    When updating, I report an error

    Warning: Attempt to modify property of non-object in /users/zalohovane/44670061/wpguru.eu/www/wp-content/plugins/wordpress-podpora/plugin-updates/plugin-update-checker.php on line 377

    Warning: Attempt to modify property of non-object in /users/zalohovane/44670061/wpguru.eu/www/wp-content/plugins/wordpress-podpora/plugin-updates/plugin-update-checker.php on line 377

    Warning: Attempt to modify property of non-object in /users/zalohovane/44670061/wpguru.eu/www/wp-content/plugins/wordpress-podpora/plugin-updates/plugin-update-checker.php on line 377

    what it is and why it appears to me 3 times?

    Thx

  11. Jānis Elsts says:

    That’s a known bug that was fixed in the latest version. Please download the client library again.

  12. Denis says:

    Plz help: Warning: The URL https://buddypress-preklady.googlecode.com/svn/trunk/wp_metadata.json?checking_for_updates=1&installed_version=1.4 does not point to a valid plugin metadata file. WP HTTP error: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in C:\Program Files (x86)\VertrigoServ\www\buddypress\wp-content\plugins\buddypress-preklady\plugin-updates\plugin-update-checker.php on line 190

  13. Jānis Elsts says:

    As the error message says, the WordPress HTTP API can’t verify the SSL certificate. Try using the HTTP version of the metadata URL instead of the HTTPS version.

  14. Denis says:

    Can you show me an example? Once I had to work, but do not know how I did it. 🙁

  15. Jānis Elsts says:

    Just use “http://buddypress-preklady.googlecode.com/svn/trunk/wp_metadata.json” instead of the “https://” version.

  16. Denis says:

    Thx, It’s working again 🙂

  17. hookedonweb says:

    How do you handle updates for paid plugins when the download_url is open to the public?

  18. Jānis Elsts says:

    There are at least two ways to handle that:

    – Omit the download URL. The user will still get update notifications, but automatic upgrades won’t be available. They’ll need to go to the plugin’s site/log into their member account/whatever to actually download the update.

    – Use license keys. addQueryArgFilter() lets you modify the HTTP request the library sends to the update server. You can use it to append the license key to the request. Have your server check the key and only output the download URL if the license is valid.

  19. Oliver says:

    Can you confirm whether or not the update checker library is compatible with the latest WP release?

    Thanks.

Leave a Reply