Get it All
Together

It recently became necessary for me to work with the WP-Cron API for a local band website. Those of you who’ve done any work with WP-Cron have no doubt noticed that the way cron jobs are held in the database can be a bit cumbersome to work with.

By this I mean: since the key under which all the arguments is held is a hash of all the arguments, they can be a bit difficult to get at when trying to reveal them or work with them in any way other than the direct API. I’m sure someone more familiar with the inner workings of the API could provide a decent explanation of why this is so, but I certainly cannot.

So in working with crons – I needed a way to be able to quickly visualize the crons setup by my plugin, which emailed a post like a mailing list, to delete any jobs sent in error – I had to come up with some functions that properly dealt with the WP-Cron array. I submit these functions to you now in hopes that this example might help someone else down the line:

Get the Schedule:


function bhd_get_schedule() {
$crons = _get_cron_array();
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {

if ( isset( $cron['bhd_cron_send_hook'] ) ) {
foreach($cron['bhd_cron_send_hook'] as $md => $stuff) {
$result[$timestamp] = $stuff['args'];
}
}
}
return $result;
}

Notice that this is really just a modification of the get_schedule() function already a part of the wp-cron API. However, what I’ve done in this case is simply provide a convenient way to bypass the hash and return a list of crons and their arguments, so they can be worked with conveniently. In my case, I only wanted one particular cron hook. If you have more than one, you might make the function take an argument that it then supplies to the isset line.

Displaying and Deleting Jobs


function bhd_delete_jobs($form) {
$jobs = bhd_get_schedule();
$deleted = 0;
foreach($form['cron_job'] as $input=>$timestamp) {
if ( wp_unschedule_event($timestamp, 'bhd_cron_send_hook', $jobs[$timestamp]) ) {
$deleted++;
}
}
return($deleted);
}


<?php if($jobs = bhd_get_schedule()) { ?>

Currently Scheduled Deliveries

Below is a list of the currently scheduled mailing list deliveries, meaning each represents an email with a batch of fifty mailing list members as recipients.

<input type="hidden" value="96f539126e" name="_wpnonce" id="_wpnonce"/>
<input type="hidden" value="/testing/wp-admin/options-general.php?page=bhd_mailinglist.php" name="_wp_http_referer"/>

<?php foreach($jobs as $job=>$args) { ?>

<?php } ?>

<?php echo(date('l jS of F Y h:i:s A', $job) ); ?gt; <?php print($args['subject']); ?> <input type="checkbox" value="<?php echo($job); ?>" name="cron_job[]" />
<input type="hidden" id="bhd_ml_cron-submit" name="bhd_ml_cron-submit" value="1" />
<input type="submit" value="Delete Jobs" />

<?php } ?>