Last active
September 28, 2020 02:09
-
-
Save UVLabs/f26c0f987778592451440982cb63d523 to your computer and use it in GitHub Desktop.
Check if a WordPress cron event is firing and show a notice if not
This file contains hidden or 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 | |
/* | |
Usecase: | |
You might have an important task within your plugin/theme that requires WP CRON working flawlessly. If a user website has little traffic, WP CRON is turned off via wp_config.php, or there is an issue with WP CRON; your scheduled task will not fire. | |
The code below allows you to set a value in minutes after which a notice(or whatever else you might want to happen) would appear in the user admin dashboard. | |
Users can permanently dismiss the notice. | |
prefix_cron_job is the hook for your scheduled task. | |
Change instances of "prefix" to suit your plugin/theme. | |
*/ | |
function prefix_cron_event_status_notice() { | |
$user_id = get_current_user_id(); | |
if ( get_user_meta( $user_id, 'prefix-cron-event-status-notice-dismissed' ) ) { | |
return; | |
} | |
$prefix_next_task_hit = wp_next_scheduled( 'prefix_cron_job' ); | |
$prefix_current_time = time(); | |
// if sharing not started cron event will not be present | |
if ( ! $prefix_next_task_hit ) { | |
return; | |
} | |
$prefix_cron_elapsed_time = ( $prefix_current_time - $prefix_next_task_hit ) / 60; | |
$prefix_cron_elapsed_time = absint( $prefix_cron_elapsed_time ); | |
// default: 60 minutes | |
$prefix_cron_event_excess_elapsed_time = apply_filters( 'prefix_cron_event_excess_elapsed_time', 60 ); | |
// if it's been more >= 60 minutes since the event was due to fire | |
if ( $prefix_cron_elapsed_time >= $prefix_cron_event_excess_elapsed_time ) { | |
?> | |
<div class="notice notice-error"> | |
<?php echo sprintf( __( '%1$s%2$sYour Plugin/Theme Name:%3$s There might be an issue preventing Plugin/Theme Name from [performing important task]. See %4$shere for solutions.%5$s%6$s%7$s', 'plugin-theme-text-domain' ), '<p>', '<b>', '</b>', '<a href="https://example.com/docs/how-to-create-true-cron-for-wp" target="_blank">', '</a>', '<a style="float: right;" href="?prefix-cron-event-status-notice-dismissed">Dismiss</a>', '</p>' ); ?> | |
</div> | |
<?php | |
} | |
add_action('admin_notices', 'prefix_cron_event_status_notice'); | |
function prefix_dismiss_prefix_event_not_firing_notice() { | |
$user_id = get_current_user_id(); | |
if ( isset( $_GET['prefix-cron-event-status-notice-dismissed'] ) ) { | |
add_user_meta( $user_id, 'prefix-cron-event-status-notice-dismissed', 'true', true ); | |
} | |
} | |
add_action('admin_init', 'prefix_dismiss_prefix_event_not_firing_notice'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment