A better way
Article     |     Published April 2020

It’s all gone CRON! How to efficiently run cron jobs on WordPress multisite

woman covering face using wall clock

WordPress is fantastic, and multisite is even better. As an agency it allows us to easily manage our client websites whilst also giving customers the ability to manage their own sites. However, WordPress has a terrible little secret – by default, it checks for and runs background tasks every time a visitor comes to any web page on the entire network. This can cause  huge problems for server load and can often bring a server to its knees.

Instead, it’s better practice to execute these background tasks once per minute per site. To do this, we execute the cron jobs via the command line.

This is all well and good for a single site version of WordPress, but for multisite we need to execute these background tasks on every single site, and WordPress doesn’t have a simple way to do this. Fortunately, there is a quick and simple way around this.

In the root of WordPress we create a new file called `wp-multisite-cron.phg` and place the following code:

<?php

// Load WordPress
require_once( dirname( __FILE__ ) . '/wp-load.php' );

global $wp_version;

// Load all the websites
$args  = array( 'archived' => 0, 'deleted' => 0, 'public' => 1 );
$websites = get_sites( $args );

// Loop through all the websites and trigger their CRON job
echo "Running Crons: " . PHP_EOL;
$agent = 'WordPress/' . $wp_version . '; ' . home_url();
$time  = time();

foreach ( $websites as $website ) {
    $domain  = $website->domain;
    $path    = $website->path;
    $command = "https://" . $domain . ( $path ? $path : '/' ) . 'wp-cron.php?doing_wp_cron=' . $time . '&ver=' . $wp_version;

    $ch = curl_init( $command );
    $rc = curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
    $rc = curl_exec( $ch );
    curl_close( $ch );

    print_r( $rc );
    print_r( "\t✔ " . $command . PHP_EOL );
}

Now on our server we can setup a simple scheduled task to run the above code to ensure that background tasks are running on WordPress without causing server overload:

* * * * * 	user 	php /path/to/wp-multisite-cron.php

 

Head Office

1A Manor Farm Woodford Halse Northamptonshire NN11 3UB

Studio

55a High Street Bridgnorth Shropshire WV16 4DX