Skip to content

Instantly share code, notes, and snippets.

@bugnumber9
Created July 29, 2025 13:38
Show Gist options
  • Select an option

  • Save bugnumber9/887807ae9c5c334ac09ced508826cd44 to your computer and use it in GitHub Desktop.

Select an option

Save bugnumber9/887807ae9c5c334ac09ced508826cd44 to your computer and use it in GitHub Desktop.
<?php
require( 'wp-load.php' ); // Make sure to set the correct path to wp-load.php file
set_time_limit( 300 ); // Optional, yet might be necessary depending on the server configuration
// BEGIN Configuration
$admin_email = 'email@example.com';
$max_log_size_bytes = 1024 * 1024; // 1 MB
$log_file = '/home/user/multisite-cron.log';
$timestamp = date( 'Y-m-d H:i:s' );
$sleep_time = 3;
// END Configuration
$errors = [];
file_put_contents( $log_file, "\n\n[$timestamp] Starting WP Multisite cron execution\n", FILE_APPEND );
if ( is_multisite() ) {
$sites = get_sites();
foreach ( $sites as $site ) {
$site_url = get_site_url( $site->blog_id );
$command = $site_url . '/wp-cron.php?doing_wp_cron';
// Optional: switch_to_blog for future use
//switch_to_blog( $site->blog_id );
//wp_suspend_cache_addition( true );
$response = wp_remote_get( $command, [
'timeout' => 15,
'blocking' => false,
] );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
$errors[] = "[$timestamp] [ERROR] {$site_url}: $error_message";
file_put_contents( $log_file, end($errors) . "\n", FILE_APPEND );
} else {
file_put_contents( $log_file, "[$timestamp] [OK] Triggered cron for {$site_url}\n", FILE_APPEND );
}
// Optional: switch_to_blog for future use
//wp_suspend_cache_addition( false );
//restore_current_blog();
sleep( $sleep_time );
}
}
file_put_contents( $log_file, "[$timestamp] Finished WP Multisite cron execution\n", FILE_APPEND );
// Email alert on failures
if ( ! empty( $errors ) ) {
$subject = 'WP Multisite Cron Failures';
$body = "Some WP Cron requests failed:\n\n" . implode( "\n", $errors );
wp_mail( $admin_email, $subject, $body );
}
// Email alert on log size
$log_size = file_exists( $log_file ) ? filesize( $log_file ) : 0;
if ( $log_size >= $max_log_size_bytes ) {
$subject = 'WP Multisite Cron Log Size Warning';
$body = "The cron log file has reached " . round( $log_size / 1024, 2 ) . " KB.\n\nConsider rotating or cleaning the log:\n{$log_file}";
wp_mail( $admin_email, $subject, $body );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment