REST API & Developer PHP Intermediate

Add a Custom Cron Interval and Scheduled Task

Add a "Every 15 minutes" schedule to WP-Cron and use it to run your own task in the background.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 19 lines
add_filter( 'cron_schedules', function ( array $schedules ): array {
	$schedules['nahnu_15_minutes'] = [
		'interval' => 15 * MINUTE_IN_SECONDS,
		'display'  => 'Every 15 minutes',
	];
	return $schedules;
} );

// Schedule the task once. WordPress keeps it scheduled after that.
add_action( 'init', function (): void {
	if ( ! wp_next_scheduled( 'nahnu_every_15_minutes' ) ) {
		wp_schedule_event( time() + MINUTE_IN_SECONDS, 'nahnu_15_minutes', 'nahnu_every_15_minutes' );
	}
} );

// The task itself.
add_action( 'nahnu_every_15_minutes', function (): void {
	delete_expired_transients();
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WP-Cron comes with hourly, twice daily, daily and weekly schedules. For tasks that need to run more often, like syncing stock or clearing a queue, you can add your own.

How it works

The cron_schedules filter adds a new interval, here 900 seconds. On init, wp_next_scheduled() checks whether the event already exists, and wp_schedule_event() creates it if not.

Every 15 minutes WordPress fires the nahnu_every_15_minutes action, which runs your task. The example clears expired transients.

Things to watch

  • WP-Cron only runs when someone visits the site. For exact timing, see “Use a Real Server Cron Instead of WP-Cron”.
  • If you remove this snippet, clear the event with wp_clear_scheduled_hook( 'nahnu_every_15_minutes' );, or WordPress will keep trying to run it.

How to test it

Install WP Crontrol, or run wp cron event list. You should see nahnu_every_15_minutes with the 15 minute schedule.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only