Add a cron job to WP via code snippet

Here is a brief code snippet that allows you to execute code on your site as a cron job. These are great for maintenance checks, database updates, email campaigns, user verifications etc.

// Declare an action with the code that you would like execute as cron 
add_action('my_first_event', 'do_something_cron');
 
function activate_my_first_cron() {
    if ( !wp_next_scheduled( 'my_first_event' ) ) {
        wp_schedule_event(time(), '<hourly>', 'my_first_event');
    }
}
 
add_action('wp', 'activate_my_first_cron');
 
function do_something_cron() {
//so something
}

Notice that the wp_schedule_event() function requires the time frequency of when to execute the cron. The frequency is a pre-defined WP string. You can use wp_get_schedules() to a full list of options.

Important notes about WP crons – the crons are only activated when someone visits the website on the front end (not in the Dahsboard). If there is no traffic on your site for 24h, none of crons will be executed. If you have an hourly cron configured, the cron will run the first time when a visitor loads site, and again after an hour or at the next site visit (whichever comes last).

You can check if your cron is being executed in the Dashboard. Install WP Crontrol and go to Tools->Cron Events and search for name you have your cron in the wp_schedule_event() call. In our case it is “my_first_event”.