Autoupdate WordPress Site Plugins with WP-CLI Bash Script Cronjob

We all know how important it is to keep your WordPress plugins updated to maintain security and avoid being hacked. A WordPress plugin vulnerability database is maintained by WPScan and can be found here. It is a tedious task to update multiple WordPress installations, some tools exist like ManageWP and InfiniteWP to ease the monotony.

I like to automate things so I wrote a bash script that uses the power of WP-CLI which is a powerful command line tool for managing WordPress. I run this script as a daily cronjob. One drawback of updating WordPress quickly is you can encounter new bugs, to mitigate that scenario the bash script takes a backup of all WordPress sites and databases prior to updating so you can easily restore.

Autoupdate WordPress Plugins with WP-CLI Cronjob

The script does the following

  • Creates a list of your WordPress sites
  • Back up WordPress folder and database
  • Update WordPress plugins
  • Set recommended WordPress file and folder permissions

You will need WP-CLI installed. A very basic installation can be done with these commands

sudo wget -q https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar -O /usr/bin/wp
sudo chmod 755 /usr/bin/wp

Create a new WordPress backup script file

mkdir ~/scripts
nano ~/scripts/wp-cli-backup.sh

Here is the WP-CLI script for backing up WordPress and automatically updating the plugins

#!/usr/bin/env bash
# Mike from https://guides.wp-bullet.com/

#where you want to store backups
BACKUPPATH=~/backups
#path to WordPress installations
SITESTORE=/var/www

#create array of sites based on folder names
SITELIST=($(ls -lh $SITESTORE | awk '{print $9}'))
#make sure the backup folder exists
mkdir -p $BACKUPPATH

#start the loop
for SITE in ${SITELIST[@]};
do
    echo Updating in $SITE
    #enter the WordPress folder
    cd $SITESTORE/$SITE
    #back up the WordPress folder
    tar -czf $BACKUPPATH/$SITE.tar .
    #back up the WordPress database
    wp db export $BACKUPPATH/$SITE.sql --allow-root
    tar -czf $BACKUPPATH/$SITE.sql.gz $BACKUPPATH/$SITE.sql
    rm $BACKUPPATH/$SITE.sql
    wp plugin update --all --allow-root;
done

#Fix permissions
sudo chown -R www-data:www-data $SITESTORE
sudo find $SITESTORE -type f -exec chmod 644 {} +
sudo find $SITESTORE -type d -exec chmod 755 {} +

Make sure the WP-CLI script is executable.

sudo chmod +x ~/scripts/wp-cli-backup.sh

Test the script manually before adding it as a cronjob.

bash ~/scripts/wp-cli-backup.sh

Add the WP-CLI backup script to as a cronjob

crontab -e

Enter this line to run the WP-CLI backup script at midnight every day

@daily /usr/bin/bash ~/scripts/wp-cli-backup.sh

That does it, every day at midnight the script will back up WordPress and update all plugins for you.

Sources and Inspiration

Sucuri Secure WordPress Backup Update
Advanced WordPress Facebook Group
Cronjob Timing