Running WP-Cron on Multisite networks the right way?

After you’ve added the constant in wp-config.php

defined('DISABLE_WP_CRON') or define('DISABLE_WP_CRON', true);

WP-CLI

And assuming you have your config.yml setup correctly, you can ommit the --path flag when calling cron run.


wp cron event run --due-now

[<hook>…]
One or more hooks to run.

[--due-now]
Run all hooks due right now.

[--all]
Run all hooks.


To run all due cron tasks in order:

function run_crons_due_now_in_order { for SITE_URL in $(wp site list --fields=url --format=csv | tail -n +2 | sort); do wp cron event run --due-now --url="$SITE_URL" && echo -e "\t+ Finished crons for $SITE_URL"; done; echo "Done"; }; run_crons_due_now_in_order;

If you want them to run concurrently (running the non-site-specific cron first):

function run_all_crons_due_now { for SITE_URL in $(wp site list --fields=url --format=csv | tail -n +2 | sort); do wp cron event run --due-now --url="$SITE_URL" && echo -e "\t+ Finished crons for $SITE_URL" & done; wait $(jobs -p); echo "Done"; }; run_all_crons_due_now;

You would want to put either option in an executable file

chmod +x run_all_wp_cron_events_due_now.sh

add a crontab task

crontab -e

and probably execute each minute

* * * * * run_all_wp_cron_events_due_now.sh > /dev/null

If you want to run a custom command from cron, you might need to specify the full paths for wp-cli to work.

* * * * * cd /home/username/public_html; /usr/local/bin/php /home/username/wp-cli.phar your-custom-cron-commands run >/dev/null 2>&1

PHP

The only reason you would need to load up WordPress here is to gather the URLs from the database rather than using a pre-defined list. We’re only going to ping those URLs and we don’t really care what the response is.

custom-cron.php

<?php

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

// Check Version
global $wp_version;
$gt_4_6 = version_compare( $wp_version, '4.6.0', '>=' );

// Get Blogs
$args  = array( 'archived' => 0, 'deleted' => 0, 'public' => 1 );
$blogs = $gt_4_6 ? get_sites( $args ) : @wp_get_sites( $args ); // >= 4.6

// Run Cron on each blog
echo "Running Crons: " . PHP_EOL;
$agent="WordPress/" . $wp_version . '; ' . home_url();
$time  = time();

foreach ( $blogs as $blog ) {
    $domain  = $gt_4_6 ? $blog->domain : $blog['domain'];
    $path    = $gt_4_6 ? $blog->path : $blog['path'];
    $command = "http://" . $domain . ( $path ? $path : "https://wordpress.stackexchange.com/" ) . '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 );
}

And add a single call to your custom-cron.php in a crontab

* * * * * wget -q -O - http://your-site.com/custom-cron.php?doing_wp_cron

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)