Created
August 11, 2014 16:23
-
-
Save vienhoang/88e1c347bdb513f200d5 to your computer and use it in GitHub Desktop.
WordPress: Custom cron job
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: VH Cron | |
Plugin URI: http://vienhoang.com | |
Description: Demo for running WP Cron Jobs | |
Version: 1.0 | |
Author: Vien Hoang | |
Author URI: http://vienhoang.com | |
License: GPL2 | |
*/ | |
// Load when wp loads | |
add_action( 'init', function() { | |
$time = wp_next_scheduled( 'vh_cron_hook' ); | |
wp_unschedule_event( $time, 'vh_cron_hook' ); | |
// Send an email for first time when nothing is scheduled | |
if ( ! wp_next_scheduled( 'vh_cron_hook' ) ) { | |
// wp_schedule_event( time(), 'daily', 'vh_cron_hook' ); | |
// Schedule an singel once | |
wp_schedule_single_event( time() + 3600, 'vh_cron_hook' ); | |
} | |
} ); | |
add_action( 'admin_menu', function() { | |
add_options_page( 'Cron Settings', 'Cron Settings', 'manage_options', 'vh_cron', function() { | |
$cron = _get_cron_array(); | |
$schedules = wp_get_schedules(); | |
?> | |
<div class="wrap"> | |
<h2>Cron Events Scheduled</h2> | |
<?php | |
foreach ( $schedules as $name ) { | |
echo "<h3>". $name['display'] . ": " . $name['interval'] . "</h3>"; | |
} | |
?> | |
</div> | |
<?php | |
} ); | |
} ); | |
// Send an email | |
add_action( 'vh_cron_hook', function() { | |
$str = time(); | |
wp_mail( 'vieninsweden@gmail.com', 'Scheduled with WP_Cron!', "This email was sent as {$str}." ); | |
} ); | |
// Custom cron intervals | |
add_filter( 'cron_schedules', function( $schedules ) { | |
$schedules['two-minutes'] = array( | |
'interval' => 120, | |
'display' => 'Every Two Minutes' | |
); | |
$schedules['ten-minutes'] = array( | |
'interval' => 600, | |
'display' => 'Every Ten Minutes' | |
); | |
return $schedules; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment