Implementing Automatic Background Updates in a Self-Hosted Plugin (Part 2)

In Part 1 of this article, we discussed the steps needed to make your self-hosted plugin (aka: a plugin that is not hosted in the plugins repository) aware of updates when you want to release new code. Now in Part 2, we’ll take a look at the code required to have your WordPress installation automatically install those updates for you.

Note: This code will only work in WordPress 3.7 or above! Version 3.7 is when WordPress added the filters required for the following code to work. But honestly, you wouldn’t seriously be running an out-of-date version of Core anyway, right?

For the truly adventurous, WordPress has made it simple to turn on automatic updates for all of your installed plugins with the following code.

add_filter( 'auto_update_plugin', '__return_true' );

So that’s fairly straightforward: return True when calling this filter and every single plugin installed on your website will automatically download and install new versions of itself.

Of course, you probably want to be a bit more selective and only keep a few trusted plugins up to date – or, more realistically/responsibly, you only want to keep your own plugin up to date. We can do this by changing the `__return_true` parameter to a function call instead.

function include_with_auto_update ( $update, $plugin ) {

    $pluginsToUpdate[] = 'myPlugin/myPlugin.php';
    $pluginsToUpdate[] = 'bruteprotect/bruteprotect.php';
    $pluginsToUpdate[] = 'all-in-one-wp-security-and-firewall/wp-security.php';

    $pluginName = $plugin->plugin;  // Retrieves base path of the passed $plugin object

    // return true to allow update to go ahead for the specified plugin
    if ( in_array( trim( $pluginName ), $pluginsToUpdate ) ) {
        return true;     
    } else {
        return false;

add_filter( 'auto_update_plugin', 'include_with_auto_update', 10, 2 );

In this example I’m demonstrating how you can easily add any number of plugins to your “whitelist” of plugins that you would like to keep up to date by using the `$pluginsToUpdate[]` array – but again, you typically should only include your own plugin to this list. This function will be called for each plugin inside the plugins array by Core when it attempts to perform auto-updates. For each plugin that returns `true`, that plugin will automatically download and install itself without you needing to lift a finger.

And that’s it! WordPress will execute its scheduled task (otherwise known as a cron job) daily, at which point this code will execute.

If you have any questions, feel free to comment below. Happy updating!

Leave a Reply