Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Last active September 4, 2021 07:01
Show Gist options
  • Save harisrozak/503be7ebd546e412b0ccf7f49f501f98 to your computer and use it in GitHub Desktop.
Save harisrozak/503be7ebd546e412b0ccf7f49f501f98 to your computer and use it in GitHub Desktop.
WP Cron with wp_schedule_event()
<?php
/**
* Register the cron on plugin loaded.
* Valid values for the recurrence are ‘hourly’, ‘daily’, and ‘twicedaily’.
* @return void
*/
function harisrozak_register_wp_cron() {
if ( ! wp_next_scheduled( 'harisrozak_wp_cron' ) ) {
wp_schedule_event( time(), 'twicedaily', 'harisrozak_wp_cron' );
}
}
add_action( 'plugins_loaded', 'harisrozak_register_wp_cron', 1401 );
/**
* Unregister the cron on plugin deactivation.
* @return void
*/
function harisrozak_unregister_wp_cron() {
wp_clear_scheduled_hook( 'harisrozak_wp_cron' );
}
register_deactivation_hook( HARISROZAK_PLUGIN_FILE, 'harisrozak_unregister_wp_cron' );
/**
* The cron function to run periodically.
* @return void
*/
function harisrozak_wp_cron_function() {
wp_mail( '[email protected]', 'Automatic email', 'Automatic scheduled email from WordPress.');
}
add_action( 'harisrozak_wp_cron', 'harisrozak_wp_cron_function', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment