WP_QUERY returns empty set when fired from a WP-CRON scheduled event

I’m trying to build a wp cron schedule to check hourly if we need to send email reminders to user satisfying specific criteria.

My setup looks like this

  • I have a reminders class that takes care of doing a all the WP query filtering, and setting up my emails, updating my posts once the email was sent, etc for the CPT satisfying the specified criteria.
  • In that class, I have a hook in my _construct() function to add to my public function do_reminders() to my scheduled event.
  • My scheduled event has been added at plugin activation
  • I’m creating my reminders object hooked to init so the construct can add the do_reminders function to the scheduled hook
  • I’m using Core Control plugin to make sure my do_reminders function is hooked to my scheduled event, and it is.

The Issue

While the scheduled event runs, it doesn’t send out the reminders it should.

If I test my do_reminders function by running it at init it will work, but when the schedule event fires it, it seems my query returns an empty set.

So my questions would be, how to debug this? What is really happening here? Are scheduled event fired before query objects are accessible?

I’ve tried to understand why my function works if I call it directly from ‘init’ like this

add_action( 'init', 'my_test_check');
function my_test_check(){
  $reminders = new MY_Reminders();
  $reminders->do_reminders();
}

but when it’s called like this

add_action( 'my_scheduled_hook', 'my_test_check');
function my_test_check(){
  $reminders = new MY_Reminders();
  $reminders->do_reminders();
}    

my query returns an empty set, so basically nothing is sent out! I’m running out of ideas at to why this happens and what to test next

1 Answer
1

Ok I spent an awful amount of time trying to debug this! Searching around I used $wpdb->queries along with define( 'SAVEQUERIES', true ); to debug queries made when wp-cron was running.

then I found out that when cron jobs were running, my query was set to 'post_status' => trash! No wonder I didn’t get any errors and as it turns out, I was trying out a specific query the other day and there was this function still running in my theme functions.php and only affecting non logged in users which was overriding my cron query!

So long story short, nothing to do with wp-cron or wp_query (and even my code), clean up after your tests (I should know better ::facepalm) and make use of debugging tools to help you find the culprit!

Leave a Comment