WordPress cron jobs not firing

I have a wordpress website that allows a user to set up a reminder for a certain day, it stores it in a database where it can either be displayed when the user logs in, or send out an email to them.

I followed the example code given in http://codex.wordpress.org/Function_Reference/wp_cron and have placed the code below into the main .php file of a plugin I have written which functions perfectly in all other ways.

Read More
if ( ! wp_next_scheduled( 'checkReminderEmails' ) ) {
    wp_schedule_event( 1411693200, 'daily', 'checkReminderEmails' );
}                    //1411693200 is the unix timestamp for 1am a couple of days ago

add_action( 'checkReminderEmails', 'sendReminderEmails' );

function sendReminderEmails() 
{
    $table_name = $wpdb->prefix."reminders";
    $query = "SELECT * FROM $table_name WHERE sendReminder = 1 and reminderDate = CURRENT_DATE( )";

    $appointments = $wpdb->get_results( $query); 
        foreach ( $appointments as $info ) 
        {
            $message = "Hello here is your reminder.";
            $toAddress = $info->userEmail;
            $subject = "This is your reminder.";
            wp_mail( $toAddress, $subject, $message);
        }
} // end sendReminderEmails()

I have checked the wp_options table in my PHP database and can see the following code there

{s:18:"sendReminderEmails";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1411693200;a:1:

I can receive other emails from the website using wp_mail() so I know that the functionality is supported by the server, and I know that the wp_cron jobs aren’t fired until the website is visited after the time has passed, but I have been unable to get this cron job to fire correctly. Am I missing something obvious?

Edit: For anybody wondering, I used the wp-cron-dashboard plugin (https://wordpress.org/plugins/wp-cron-dashboard/) despite the warning that it hasn’t been updated in 2+ years to check that my cron job was scheduled properly.

I also had to add global $wpdb; to the top of my function, the reason it was failing to fire was because without declaring that I was unable to use the get_results() function.

I also discovered that if you go to wp-cron.php you will manually force any scheduled cron jobs to be fired, and all output will display there, so it is possible to debug a cron job by adding echo statements and going to that page.

Related posts

Leave a Reply

1 comment

  1. I know this is old but one thing I see right away is you need global $wpdb; as the first line of the sendReminderEmails() function, otherwise it’s going to bomb.

    I often quickly test cron functions in my front-page.php by adding something like sendReminderEmails(); exit; to the top, just as a sanity check that the function works at all.