一般情况下 WordPress 的计划任务是由用户的访问行为触发的,如果网站流量比较少(或者没有任何流量),那么定时任务就可能很难被触发(或者根本不会被触发),这会导致一些重要的计划任务(比如 security bug fix)被搁置,使用 Linux 系统自带的计划任务(Cronjob)可以解决这个问题。
本文介绍 WordPress Mu 多站点模式的系统定时任务设置方法,设置一次所有站点都会得到更新。
安装 WP-Cli
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar chmod +x wp-cli.phar sudo mv wp-cli.phar /usr/local/bin/wp
关闭 WordPress 默认的计划任务
在 wp-config.php 中加入:
define( 'DISABLE_WP_CRON', true );
新增一个 Shell 脚本
/usr/local/bin/mucron.sh:
#!/bin/bash # Fill Your WordPress PATH WP_PATH="/path/to/wp" # Check if WP-CLI is available if ! hash wp 2>/dev/null; then echo "WP-CLI is not available" exit fi # If WordPress isn’t installed here, we bail if ! $(wp core is-installed --path="$WP_PATH" --quiet); then echo "WordPress is not installed here: ${WP_PATH}" exit fi # Get a list of site URLs if $(wp core is-installed --path="$WP_PATH" --quiet --network); then SITE_URLS=`wp site list --fields=url --archived=0 --deleted=0 --format=csv --path="$WP_PATH" | sed 1d` else SITE_URLS=(`wp option get siteurl --path="$WP_PATH"`) fi # Loop through all the sites for SITE_URL in $SITE_URLS do # Run all event hooks that are due for EVENT_HOOK in $(wp cron event list --format=csv --fields=hook,next_run_relative --url="$SITE_URL" --path="$WP_PATH" | grep now$ | awk -F ',' '{print $1}') do wp cron event run "$EVENT_HOOK" --url="$SITE_URL" --path="$WP_PATH" --quiet done done
给予可执行权限:
chmod +x /usr/local/bin/mucron.sh
用 Crontab 设置计划任务
crontab -e
并且加入:
*/30 * * * * su -s /bin/bash -c '/usr/local/bin/mucron.sh' www
在 ~/.profile 中加入:
export HTTP_HOST='localhost'
执行:
source ~/.profile
重启 cron 服务
/etc/init.d/cron restart
尝试运行脚本:
su -s /bin/bash -c '/usr/local/bin/mucron.sh' www
如果没有错误提醒,那么就算成功了。
文章评论