使用WP CLI批量更新WordPress站点

场景:一台Debian机器下有500+worpdrsss站点,需将所有站点的wordpress程序、主题、插件,还有Woocommerce商店都更新到最新版。

首先 sudo apt update && apt upgrade -y 更新一下。

安装 WP CLI

#安装 WP CLI
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

#检测phar文件工作状态
php wp-cli.phar --info

#给wp-cli.phar文件增加可执行权限,并调整为可使用wp命令来执行
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

#验证
wp --info

#输出如下
OS:     Linux 5.10.0-18-amd64 #1 SMP Debian 5.10.140-1 (2022-09-02) x86_64
Shell:  /bin/bash
PHP binary:     /www/server/php/80/bin/php
PHP version:    8.0.20
php.ini used:   /www/server/php/80/etc/php-cli.ini
MySQL binary:   /usr/bin/mysql
MySQL version:  mysql  Ver 14.14 Distrib 5.7.39, for Linux (x86_64) using  EditLine wrapper
SQL modes:
WP-CLI root dir:        phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir:      phar://wp-cli.phar/vendor
WP_CLI phar path:       /root
WP-CLI packages dir:
WP-CLI cache dir:       /root/.wp-cli/cache
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.7.1

#更新 wp cli
wp cli update

执行批量更新

假设所有网站存放路径为 /www/web/,先 cd /www/web ,然后 vim wpexec.sh,内容如下,保存。

#!/bin/bash
DIR=`ls .`
for dir in ${DIR};do
	if [ -d ${dir} ];then
		echo $dir
		cp wpup.sh ${dir}
		cd ${dir}
		pwd
		./wpup.sh 
		cd ..
	fi
done

vim wpup.sh 内容如下,保存。这里要注意一下权限的问题,建议先单个执行wp core update看下。

#!/bin/bash
#更新wordrepss
wp core update --allow-root
#更新wordpress db
wp core update-db --allow-root
# 更新插件,排除 akismet和hello
wp plugin update --all --exclude=akismet,hello --allow-root
# 更新主题
wp theme update --all --allow-root
# 更新woocommerce db
wp wc update --allow-root

然后给文件增加可执行权限

chmod +x wpexec.sh
chmod +x wpup.sh

执行脚本

bash wpexec.sh

最后删除这2个文件

find . -maxdepth 2 -name 'wp*.sh' -delete

参考:

https://wp-cli.org/
https://developer.wordpress.org/cli/commands/
https://github.com/woocommerce/woocommerce/wiki/Upgrading-the-database-using-WP-CLI
https://blog.csdn.net/robinblog/article/details/8853628