How to make a snippet run once per day

Avatar

By Shea Bunge

updated 2 months ago

By default, snippets run every time your site is visited. If you want a snippet to run only once per day, you can create a cron job.

Here's an example:

add_action( 'init', function () {
	$hook = 'run_snippet_daily';
	$args = array();

	if ( ! wp_next_scheduled( $hook, $args ) ) {
		wp_schedule_event( time(), 'daily', $hook, $args );
	}
} );

add_action( 'run_snippet_daily', function () {
	// do something once each day
} );

If you want the action to run on a different schedule, you can use the keywords hourly or twicedaily in place of daily.

Did this answer your question?