WordPress cron jobs not running – Resolved

Recently, I worked with a client who was experiencing cron issues on their WooCommerce subscription website. The automatic renewal of subscriptions was not processing due to cron jobs getting stuck. The client was using WP Cron Control and another plugin for monitoring cron jobs. Their site was hosted on Bluehost.

Upon taking on the project, I reviewed the error log and discovered a fatal error caused by the Bluehost WordPress plugin. Disabling this plugin did not resolve the issue. To address the problem temporarily, I wrote a function that executed overdue cron jobs, which worked temporarily. However, the client wanted to identify the root cause.

function run_past_due_cron_jobs() {
    // Get the list of all scheduled cron jobs
    $cron_jobs = _get_cron_array();

    // Check if any jobs are scheduled
    if (empty($cron_jobs)) {
        return; // Exit if no cron jobs are found
    }

    // Current timestamp
    $current_time = time();

    // Iterate over all cron events
    foreach ($cron_jobs as $timestamp => $cron_hooks) {
        // If the cron job is overdue
        if ($timestamp <= $current_time) {
            foreach ($cron_hooks as $hook => $details) {
                // Run all overdue jobs for this hook
                foreach ($details as $key => $data) {
                    // Execute the overdue task
                    do_action($hook, ...array_values($data['args']));

                    // Remove the overdue cron event
                    wp_unschedule_event($timestamp, $hook, $data['args']);
                }
            }
        }
    }
}

After implementing this function, I enabled the WP alternate cron, which appeared to resolve the issue. This led me to confirm that the problem was related to the WP cron cache. To address the issue permanently, I added the following code to the .htaccess file:

<FilesMatch "wp-cron\.php$">
    Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
    Header set Pragma "no-cache"
    Header unset ETag
    FileETag None
</FilesMatch>

This code ensures that WP Cron runs directly from the server, preventing it from being cached. I hope this solution helps others facing similar issues.

Leave a Reply

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