What is WP-Cron?
- WP-Cron is WordPress’s built-in pseudo-cron system for scheduling tasks (like publishing scheduled posts, sending emails, clearing caches).
- It runs only when a page is loaded — not continuously like a real server cron.
How to Schedule Cron Jobs in WordPress
1. Create a Custom Cron Event
function my_custom_cron_job() {
// Your code here
error_log( 'My custom cron job ran at ' . current_time( 'mysql' ) );
}
// Schedule the event if not already scheduled
if ( ! wp_next_scheduled( 'my_custom_cron_hook' ) ) {
wp_schedule_event( time(), 'hourly', 'my_custom_cron_hook' );
}
// Hook the function to the event
add_action( 'my_custom_cron_hook', 'my_custom_cron_job' );2. Custom Intervals (Optional)
add_filter( 'cron_schedules', function( $schedules ) {
$schedules['every_five_minutes'] = array(
'interval' => 300,
'display' => __( 'Every Five Minutes' )
);
return $schedules;
});Then schedule with:
wp_schedule_event( time(), 'every_five_minutes', 'my_custom_cron_hook' );3. Unschedule Events (Cleanup)
function my_remove_cron_job() {
$timestamp = wp_next_scheduled( 'my_custom_cron_hook' );
wp_unschedule_event( $timestamp, 'my_custom_cron_hook' );
}
register_deactivation_hook( __FILE__, 'my_remove_cron_job' );4. Trigger Cron via Real Server Cron (Recommended)
Because WP-Cron depends on site visits, it can be unreliable for exact timing.
Set a real server cron job to hit:
wget -q -O - https://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1or
curl https://example.com/wp-cron.php?doing_wp_cron✅ Best Practices
- Always clean up cron events on plugin/theme deactivation.
- Use custom intervals for more flexibility.
- For high-traffic or mission-critical sites, use a real cron job to trigger
wp-cron.php.
