Skip to content

Instantly share code, notes, and snippets.

@ph33nx
Last active May 23, 2024 14:13
Show Gist options
  • Save ph33nx/311bb190f6386280497762a8cb6a705c to your computer and use it in GitHub Desktop.
Save ph33nx/311bb190f6386280497762a8cb6a705c to your computer and use it in GitHub Desktop.
Wordpress Automated Themes, Plugins & Core Updates - Bash Script - Run as Cron Job
#!/bin/bash
# This script is designed to update WordPress core, plugins, and themes,
# set correct file permissions, and restart Nginx and PHP-FPM services.
# Update www-data user to the filesystem user of WP.
# !IMP: Make sure WP CLI is installed: https://wp-cli.org/
#
# Original script concept by https://github.com/ph33nx
#
# To schedule this script to run every Thursday at 4 AM, add the following line to your crontab:
# 0 4 * * 4 bash /root/wp-update.sh >> /root/wp-update.log 2>&1
#
# Make sure to replace "/path/to/your/wp-update.sh" with the actual path to this script.
# You can edit your crontab by running: sudo crontab -e
# Define the base directory. This folder has all your websites.
BASE_DIR="/usr/share/nginx/php/wordpress/"
# Ensure the script is running as root
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
# Check for wp-cli.phar existence in the system
if ! command -v wp &> /dev/null; then
echo "WP-CLI could not be found. Please install it first."
exit 1
fi
# Loop through each WordPress directory
for dir in $BASE_DIR*; do
if [ -d "$dir" ] && [ -f "$dir/wp-config.php" ]; then
echo "Updating WordPress in $dir"
# Run the wp-cli commands as the www-data user to avoid permission issues
sudo -u www-data wp --path="$dir" core update
sudo -u www-data wp --path="$dir" plugin update --all
sudo -u www-data wp --path="$dir" theme update --all
sudo -u www-data wp --path="$dir" core update-db
sudo -u www-data wp --path="$dir" wc update
# Clear WP cache
sudo -u www-data wp --path="$dir" autoptimize clear
sudo -u www-data wp --path="$dir" fastest-cache clear all and minified
sudo -u www-data wp --path="$dir" cache flush
# Set correct permissions for files and directories
find "$dir" -type f -exec chmod 644 {} \;
find "$dir" -type d -exec chmod 755 {} \;
chown -R www-data:www-data "$dir"
else
echo "Skipping $dir, no valid WordPress installation found."
fi
done
# Clearing Nginx cache
echo "Clearing Nginx cache..."
rm -rf /etc/nginx/cache/*
# Restarting services
echo "Restarting Nginx and PHP-FPM services..."
systemctl restart nginx
systemctl restart php8.2-fpm
echo "Updates and maintenance tasks completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment