Note: this code appears to have some problems based on feedback here in the comments. It worked fine for me when I used it though.

If you are running your own web server, one of the best ways to run basic administration tasks in WordPress is via the WP CLI (WordPress Command Line Interface). And if you are running your own web server, then it is smart to turn off the default WP Cron systems and using a server level Cron job instead. Tom McFarlin wrote one of the goto blog posts regarding setting this up, but his post doesn’t take the next step of incorporating WP CLI for handling this, and it doesn’t handle WordPress multisites very well, as his code requires adding new Cron tasks whenever a new site is added.

To work around these issues, I wrote the following simple bash script. It grabs a list of all sites on the multisite network via WP CLI, then loops through them all and runs all the due WP Cron tasks for each individual site. To use this, just change the PATH_TO_WORDPRESS to show the correct path to your WordPress installation.

#!/bin/bash
clear

PATH_TO_WORDPRESS="/var/www/public_html"
for URL in $(wp site list --fields=url --format=csv --path="$PATH_TO_WORDPRESS")
do
	if [[ $URL == "http"* ]]; then
		wp cron event run --all --due-now --url="$URL" --path="$PATH_TO_WORDPRESS"
	fi
done

To make this run every hour, just add something like this to your Cronjob (where /var/www/wp-cron.sh is the location of your bash script):

@hourly bash /var/www/wp-cron.sh

Feel free to adapt this for your own needs, and to publish any changes. You can consider this public domain content, but a link back to this post is always appreciated 🙂