Run a Daily Task With WP-Cron
Schedules a custom task once a day and gives you a function to fill in, for example to clean up data or send a report. Includes the scheduling and the hook.
Opens WPIDE on
Code
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpide_daily_task' ) ) {
// First run tomorrow at 03:00 site time.
$first = new DateTime( 'tomorrow 03:00', wp_timezone() );
wp_schedule_event( $first->getTimestamp(), 'daily', 'wpide_daily_task' );
}
} );
add_action( 'wpide_daily_task', function () {
// Your daily code goes here. Example: log that the task ran.
error_log( '[wpide_daily_task] ran at ' . wp_date( 'Y-m-d H:i:s' ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
} );
Notes
Put your code inside the wpide_daily_task callback. To stop the task after removing the snippet, run "wp cron event delete wpide_daily_task".
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.