How to Automate WordPress Update

Let say we manage 50 WordPress website which using some server. The best practice for any software is if there’s a stable update we’ll update after sometimes, on my terms usually one week after WordPress release. Manual update is wasting a lot of time because you need to log in one by one and click the update button.

But no need to worry, we can create a simple script to automatically WordPress update, including themes and plugins. We’ll create a wrapper that utilizes WP-CLI. I usually manage all of my websites under /var/www/{DOMAIN} folder.

Create /opt/wp.sh file the copy following script

#!/usr/bin/env bash
# Automate WordPress update
 
WPCLI='/usr/local/bin/wp'
WEBROOT='/var/www'
USER="www-data"
 
if [ "$(id -u)" != "0" ]; then
   echo "Run as root" 1>&2
   exit 1
fi
 
if [ ! -f $WPCLI ]; then
    wget -q https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar -O /usr/local/bin/wp
    chmod +x /usr/local/bin/wp
    echo "WP-CLI instalation done."
fi
 
for a in $(ls -d $WEBROOT/*/); do
        cd "$a"
        if [[ -d "wp-admin" ]]; then
            echo "WordPress: $a"
            sudo -u $USER wp core update;
            sudo -u $USER wp plugin update --all;
            sudo -u $USER wp theme update --all
        fi
        cd - &>/dev/null
done

this script runs as a root, then the update run as the webserver user itself, normally nginx, apache or www-user. Since WP-CLI using the WordPress database configuration we don’t need a separate configuration for the database, it’s straight forward installation.

Give the script executable permission

chmod +x /opt/wp.sh

Then run the script for the first time

/opt/wp.sh

What is the script do:
1. Check if wp-cli is installed, if not it’ll download the latest version.
2. Check for WordPress on every folder under /var/www
3. If WordPress is found, update core, themes, and plugins to the latest version

Output of these script

WordPress: /var/www/atetux.com/
Success: WordPress is up to date.
Success: Plugin already updated.
Success: Theme already updated.
WordPress: /var/www/SECRET/
Success: WordPress is up to date.
Enabling Maintenance mode...
Downloading update from https://downloads.wordpress.org/plugin/really-simple-ssl.5.0.5.zip...
Unpacking the update...
Installing the latest version...
Removing the old version of the plugin...
Plugin updated successfully.
Disabling Maintenance mode...
Success: Updated 1 of 1 plugins.
+-------------------+-------------+-------------+---------+
| name              | old_version | new_version | status  |
+-------------------+-------------+-------------+---------+
| really-simple-ssl | 5.0.4       | 5.0.5       | Updated |
+-------------------+-------------+-------------+---------+

that’s is, a simple script but powerful.

Leave a Comment