wp_cron()
Run all scheduled cron events whose time has come.
Checks whether there is at least one cron event whose time has come, and runs spawn_cron() which send the request to cron file: /example.com/wp-cron.php.
When calling this function, all the cron events that were planned and which time has come will be initiated.
You can read more about cron in the description of wp_schedule_event() which is used to add new cron events. There are a lot of examples and everything you need to know about cron in WordPress.
This function called by WordPress core automatically on the init event.
if ( ! defined( 'DOING_CRON' ) ) { add_action( 'init', 'wp_cron' ); }
Basically, you don't need to use this function.
This function will not work, if constant DISABLE_WP_CRON is defined.
Cron is named after a unix program which runs unattended scheduled tasks.
Read more about cron: WP Cron (scheduler) in WordPress
No Hooks.
Return
false|Int|null
.
- Number — on success — the number of performed events (0 means that there are no events to be executed now).
- false — when no event could be processed.
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. For information about casting to booleans see the PHP documentation. Use the === operator for testing the return value of this function.
Usage
wp_cron();
Examples
#1 Send an email every hour
You can place this code in, for example, functions.php.
// Schedule an event if it hasn't been scheduled yet // It's better to do it during plugin/theme activation if ( ! wp_next_scheduled( 'my_task_hook' ) ) { wp_schedule_event( time(), 'hourly', 'my_task_hook' ); } // Add a callback add_action( 'my_task_hook', 'my_task_function' ); function my_task_function() { wp_mail( '[email protected]', 'Scheduled email', 'A scheduled email from WordPress.'); }
#2 Add a cron event and a custom interval
The code must be added into the functions.php file or in plugin.
add_filter( 'cron_schedules', 'mycron_add_schedule' ); add_action( 'init', 'mycron_add_hook' ); ## Schedules an event function mycron_add_hook(){ if ( ! wp_next_scheduled( 'my_cron_worker_start' ) ) { wp_schedule_event( time(), 'my_cron_worker', 'my_cron_worker_start' ); } } ## Adds a custom interval function mycron_add_schedule(){ $schedules['my_cron_worker'] = array( 'interval' => 60, 'display' => 'My Cron Worker' ); return $schedules; }
Changelog
Since 2.1.0 | Introduced. |
Since 5.1.0 | Return value added to indicate success or failure. |
Since 5.7.0 | Functionality moved to _wp_cron() to which this becomes a wrapper. |
wp_cron() wp cron code WP 6.7.1
function wp_cron() { if ( did_action( 'wp_loaded' ) ) { return _wp_cron(); } add_action( 'wp_loaded', '_wp_cron', 20 ); }