Automating WordPress updates with wp-cli

For some time it’s been possible to automatically update the core of WordPress, ensuring that you get the latest security and bug fixes promptly. However, this functionality hasn’t been extended to plugins and themes, possibly because it’s much harder to test all the combinations that people are running.

Plugins in particular are a source of vulnerabilities for WordPress sites. Themes seem to be less of an issue — when they do have problems it’s often because of a plugin they use rather than the theme itself — but it’s good to keep them up to date regardless.

Fortunately there is a tool called wp-cli which will update core, plugins and themes, as well as other useful functionality such as search and replace — particularly useful if you change the URL of your site, e.g. when moving from HTTP to HTTPS.

I have written the following wrapper script around wp-cli, which is free for anyone to use (no attribution required, although I would love to hear from anyone who finds it useful or has suggestions for improvements):


#!/bin/bash

set -e
set -u

WP_SITES=(
  "www.phpdeveloper.org.uk"
)

for site in "${WP_SITES[@]}"
do
  site_path="/var/www/${site}/public_html"
  echo "Updating core, plugins and themes for ${site}"
  /usr/bin/php /usr/local/bin/wordpress/wp-cli.phar core update --path=${site_path}
  /usr/bin/php /usr/local/bin/wordpress/wp-cli.phar plugin update --all --path=${site_path}
  /usr/bin/php /usr/local/bin/wordpress/wp-cli.phar theme update --all --path=${site_path}
  echo
done

The script goes through a list of sites and updates core, all plugins and all themes — in that order, in case a plugin or theme update requires the latest version of core. If there are any errors, the script terminates immediately. I run the script via cron each morning during the daytime, which means if something does go wrong I get an email and am usually in a position to fix it.

Given that I host a lot of WordPress sites for myself and others, this script saves me at least a couple of hours each week, as well as reducing the window for a site to receive updates to a maximum of 24 hours. I’ve been running WordPress since version 1.5 and have come to the conclusion that the risk of having a vulnerability exposed because of a failure to update is far greater than the risk of an automated update breaking a site.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.