Schedule Cron Job Event

Overview

Use this tool to create custom code for WordPress Cron Jobs using wp_schedule_event() function.

Usage

  • Fill in the user-friendly form.
  • Click the “Update Code” button.
  • Copy the code to your project.
  • Or save it as a snippet and share with the community.

Examples

If you are still learning how to use this tool, check out the following examples:

The function used in the code.
Translation file Text Domain. Optional.
The first time you want the event to occur.
How often the event should reoccur.
Create custom intervals using the "cron_schedules" filter in wp_get_schedules().
The name of an action hook to execute.
Comma separated list of arguments to pass to the hook function(s).
Custom code to be executed.
  Save Snippet
// Scheduled Action Hook
function disable_old_posts_comments_action_hook( ) {
	global $wpdb;
	$days_to_close     = 31; // disable comments and ping backs on posts older than 31 days
	$competition_posts = 10; // mark competition posts as private after 10 days
	
	$wpdb->query(
		$wpdb->prepare(
			"UPDATE $wpdb->posts SET `comment_status` = %s, `ping_status` = %s WHERE `post_date_gmt` < DATE_SUB(%s, INTERVAL %d DAY);",
			array( 'closed', 'closed', current_time( 'mysql', 1 ), $days_to_close )
		)
	);
	
	$wpdb->query(
		$wpdb->prepare(
			"UPDATE $wpdb->posts SET `post_status` = %s WHERE `post_type` = %s AND `post_date_gmt` < DATE_SUB(%s, INTERVAL %d DAY);",
			array( 'private', 'competition', current_time( 'mysql', 1 ), $competition_posts )
		)
	);
}
add_action( 'disable_old_posts_comments_action_hook', 'disable_old_posts_comments_action_hook' );

// Schedule Cron Job Event
function disable_old_posts_comments_cron_job() {
	if ( ! wp_next_scheduled( 'disable_old_posts_comments_action_hook' ) ) {
		wp_schedule_event( current_time( 'timestamp' ), 'daily', 'disable_old_posts_comments_action_hook' );
	}
}
add_action( 'wp', 'disable_old_posts_comments_cron_job' );