Kishan Jasani

Code, Creativity & Everything I Learn

Automate your WordPress Cron

We all know WordPress Cron(wp-cron) can be unreliable if left on the default WordPress setting.

The WordPress default behaviour on maybe I will run maybe not for wp-cron in a case of sites with less traffic.

There are following solutions to solve this problem. All require disabling default WP cron.

This will work for both single and multisite WordPress installation.

  1. Linux Crontab
  2. For Scalable and time-sensitive cron jobs.

1. Linux Crontab

Create a file called: execute-wp-cron.sh

#!/bin/bash
WP_PATH="/path/to/wp" 
# Check for WP-CLI
if ! hash wp 2>/dev/null; then
	echo "WP-CLI is not installed!"
	exit
fi
# Fall back if no WP.
if ! $(wp core is-installed --path="$WP_PATH" --quiet); then
	echo "No wordpress installtion found on: ${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 all sites
for SITE_URL in $SITE_URLS
do
	wp cron event run $( wp cron event list --fields=hook,next_run_relative --format=csv --url="$SITE_URL" --path="$WP_PATH" | awk -F, '$2=="now" {print $1}' ) --url="$SITE_URL" --path="$WP_PATH" --quiet
done
WP_PATH="/path/to/wp"

Make the script executable:

chmod +x execute-wp-cron.sh

Test it by running ./execute-wp-cron.sh If it does not output anything go to next step else fall back.

Every user has their own crontab so I’ll recommend editing your Nginx / Apache user’s crontab ( www-data or http )

To edit run:

crontab -e -u {user-name}

And add the following line and update your script path

* * * * * /some/folder/execute-wp-cron.sh

This will tell Linux to check for wp-cron every minute and if there is any new cron yet to execute in a pipeline it will execute it.

You can update cron time according to your preference, This site https://crontab.guru may help to understand parameters.

2. Scalable and time-sensitive cron jobs

If you want a highly scalable cron then I strongly recommend checking the following repo:

  1. https://github.com/humanmade/Cavalcade 
  2. https://github.com/Automattic/Cron-Control

These are both methods recommended for sites with high traffic which is relying on cron and running time-critical cron.

Both require different setup you can find that on their github/product page and pick one which you feel works for you.

Disable default cron

Lastly, disable wp-cron by adding this line in wp-config.php

define( 'DISABLE_WP_CRON', true );
// Mind space WPCS.

You can test if cron is running by wp cron event list.

Leave a Reply

Your email address will not be published. Required fields are marked *