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. Hi Jānis,

    Thank you for your paitence – my apologies for missing that information in the post itself.

    David

  2. Would I be right in thinking that I could use this code to over-ride for plugins which are in the WordPress directory (or at least, have one with the same slug there)?

  3. Jānis Elsts says:

    Yes, you could probably do that.

  4. I’ll give it a try and let you know if it works or not.

  5. James says:

    Hi all,

    Need a little bit of help with passing through a license key – has anybody managed to do this? If so could you point me in the right direction… I’m using addQueryArgFilter but don’t know how to handle this on my server.

    Help!

    Thanks.

  6. Jānis Elsts says:

    I’m actually doing that in one of my commercial plugins, but the process is too complicated to explain properly in a comment. I’ll try anyway:

    – I’ve written a plugin that intercepts requests that contain specific query parameters, like “http://example.com/?get_metadata_for=productname&license_key=key”. It uses the query_vars filter to register the parameters with WordPress, then checks for their presence during the template_redirect action by using the get_query_var() function.

    – If the required parameters are present, it loads plugin metadata and prepares it for output. By default, the metadata doesn’t include a download link.

    – If the license key is present (get_query_var('license_key') != ''), it checks the customer table to see if the key is valid. If it is, the plugin adds a download link to the metadata. It also adds a bunch of licensing info (like status and expiration time).

    – Finally, the metadata is JSON-encoded and output.

    The request handler looks something like this (this is purely for illustration; you won’t be able to actually run this code):

    public function processMetadataRequest() {
    	$slug = $this->getQueryVar('get_metadata_for');
    	if ( empty($slug) ) {
    		return;
    	}
    
    	//Assume all products with the same slug also have the same download file.
    	$product = null;
    	foreach($this->products as $possibleProduct) {
    		if ($possibleProduct['slug'] == $slug && isset($possibleProduct['filename'])) {
    			$product = $possibleProduct;
    			break;
    		}
    	}
    	if ( $product === null ) {
    		wp_die('Unknown product', 'Not Found', array('response' => 404));
    	}
    
    	$filename = APH_DIRECTORY . '/' . $product['filename'];
    	$info = $this->getPluginMetadata($filename);
    
    	//If a known license key or token is specified, include the license info in the output.
    	$license = null;
    	$licenseKey = $this->getQueryVar('license_key');
    	$siteToken = $this->getQueryVar('license_token');
    	if ( !empty($licenseKey) || !empty($siteToken) ) {
    		$result = $this->licenseServer->verifyLicenseExists(
    			$slug,
    			$licenseKey,
    			$siteToken,
    			!empty($siteToken) ? strval($this->getQueryVar('license_site_url')) : null
    		);
    		if ( is_wp_error($result) ) {
    			//If the license doesn't exist, we'll output an invalid dummy license.
    			$license = new Wslm_ProductLicense(array(
    				'status' => $result->get_error_code(),
    				'error' => array(
    					'code' => $result->get_error_code(),
    					'message' => $result->get_error_message(),
    				),
    			));
    		} else {
    			$license = $result;
    		}
    	}
    
    	if ( $license !== null ) {
    		$info['license'] = $this->licenseServer->prepareLicenseForOutput($license, !empty($siteToken));
    	}
    
    	//Only include the download URL if the license is valid.
    	if ( $license && $license->isValid() ) {
    		$args = array_filter(array(
    			'get_product' => $license['product_slug'],
    			'license_key' => $licenseKey,
    			'license_token' => $siteToken,
    			'license_site_url' => $this->getQueryVar('license_site_url'),
    		));
    		$info['download_url'] = add_query_arg($args, $this->homeUrl('/'));
    	}
    
    	$output = json_encode($info);
    	header('Content-Type: application/json');
    	echo $output;
    	exit;
    }
    
  7. Brodie001 says:

    Been using this script for a while and it works great. But I found one host that it won’t work with, WP-Engine. When their caching is enabled it drops all SESSION variable . They do this for security and since WordPress doesn’t use SESSION variables for anything (http://support.wpengine.com/php-session-variables/). Is there any way to update this tool to bypass any session use and still work in a cached environment?

  8. Jānis Elsts says:

    This script doesn’t use PHP sessions anywhere. What specifically is the problem, and why do you it has something to do with sessions?

  9. […] Shadow’s libraries for automatic updates for private and commercial themes and updates for private and commercial plugins work perfectly together with IWP thus giving me the opportunity to develop a private plugin, put it […]

  10. […] server for WordPress plugins and themes. Check it out on GitHub. This is the server component to my plugin update checker and theme update checker client […]

  11. […] since the release of the Plugin Update Checker library, one of the most common questions asked has been this: “How can I secure my download […]

  12. Barbara says:

    And it might be fixed now…. I activated your child theme, then reactivated mine – and now I have a notification 🙂 Whew…..

  13. Jānis Elsts says:

    I see. In that case, the problem most likely was that it just hadn’t checked for updates yet. The “Force Update Check” plugin is pretty old and I haven’t tested it with the latest version of WordPress; maybe it doesn’t work any more.

  14. Paul says:

    Hi

    any idea why the update process fails:
    Unpacking the update…

    Installing the latest version…

    Removing the old version of the plugin…

    Could not remove the old plugin.

    Plugin update failed.

    thanks!

  15. Jānis Elsts says:

    Could it be that another process is holding one of the plugin files open? That would prevent WordPress from deleting the old version of the plugin.

    This can happen if you have a file open in an editor or if the plugin directory contains a SVN/Git repository.

  16. Devin Walker says:

    On line 377 in plugin-update-checker.php

    else {
    unset($updates->response[$this->pluginFile]);
    }

    should be:

    else {
    if($updates->response[$this->pluginFile]) {
    unset($updates->response[$this->pluginFile]);
    }
    }

    otherwise when other plugins were updating I was seeing:

    Warning: Attempt to modify property of non-object in plugin-update-checker.php on line 377

    in the error logs

  17. Jānis Elsts says:

    It sounds like you have an old version of the library. That issue has already been fixed in the current release. You can download it from GitHub.

  18. Mark Bailey says:

    Sorry if this is a dumb question, but:

    If I want to use this technique for multiple plugins, does each one need a jSON info file? Or can there be one file containing info for each plugin?

    Thanks,

    Mark

  19. Jānis Elsts says:

    Yes, each plugin needs its own file.

Leave a Reply