Skip to content

Instantly share code, notes, and snippets.

@2ndkauboy
Last active December 11, 2016 18:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save 2ndkauboy/fed0e677791da91404ba14475e6ce83a to your computer and use it in GitHub Desktop.
An example plugin for minutely tasks using WP-Cron
<?php
/**
* WP-Cron Minutely
*
* @package WPCronMinutely
* @author Bernhard Kau
* @license GPLv3
*
* @wordpress-plugin
* Plugin Name: WP-Cron Minutely
* Plugin URI: https://kau-boys.com
* Description: An example plugin for minutely tasks using WP-Cron
* Version: 1.0.0
* Author: Bernhard Kau
* Author URI: https://kau-boys.com
* License: GPLv3
* License URI: http://www.gnu.org/licenses/gpl-3.0
*/
add_action( 'init', 'wp_cron_minutely_init' );
register_deactivation_hook( __FILE__, 'wp_cron_minutely_deactivate' );
/**
* Add the schedules interval, cron hook and schedules the events.
*/
function wp_cron_minutely_init() {
add_filter( 'cron_schedules', 'wp_cron_minutely_add_cron_schedules' );
add_action( 'wp_cron_minutely_cron_hook', 'wp_cron_minutely_cron_exec' );
if ( ! wp_next_scheduled( 'wp_cron_minutely_cron_hook' ) ) {
wp_schedule_event( time(), '1min', 'wp_cron_minutely_cron_hook' );
}
}
/**
* Add a minutely interval for wp_cron.
*
* @param array $schedules The schedules intervals array.
*
* @return array
*/
function wp_cron_minutely_add_cron_schedules( $schedules ) {
if ( ! isset( $schedules['1min'] ) ) {
$schedules['1min'] = array(
'interval' => 60,
'display' => esc_html__( 'Every minute', 'wp-cron-minutely' ),
);
}
return $schedules;
}
/**
* Increments an option by 1 every time the hook was called
*/
function wp_cron_minutely_cron_exec() {
if ( $calls = get_option( 'wp_cron_minutely_cron_hook_calls' ) ) {
update_option( 'wp_cron_minutely_cron_hook_calls', $calls + 1 );
} else {
add_option( 'wp_cron_minutely_cron_hook_calls', 1 );
}
}
/**
* Remove the scheduled task on plugin deactivation.
*/
function wp_cron_minutely_deactivate() {
$timestamp = wp_next_scheduled( 'wp_cron_minutely_cron_hook' );
wp_unschedule_event( $timestamp, 'wp_cron_minutely_cron_hook' );
delete_option( 'wp_cron_minutely_cron_hook_calls' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment