Get started with 33% off your first certification using code: 33OFFNEW

How to schedule an action in WP cron

2 min read
Published on 22nd November 2023
How to schedule an action in WP cron

WP Cron is a powerful tool in WordPress that allows you to schedule actions to occur at specific intervals. This functionality is essential for tasks like publishing scheduled posts, performing regular backups, or custom tasks like sending out daily emails. Understanding how to schedule actions with WP Cron is a valuable skill for any WordPress site administrator or developer. Let's break down the process into manageable steps.

Understanding WP Cron

Unlike a traditional cron job, which relies on the system clock, WP Cron works by checking for scheduled tasks to run on every page load. It's important to note that if your site has low traffic, WP Cron might not be as reliable without additional configuration.

Step 1: Creating a Custom Function

Firstly, you need to decide what action you want to schedule. Let's say you want to delete temporary files daily. You'll start by creating a custom function in your theme's functions.php file or in a custom plugin.

function delete_temp_files() {
    // Code to delete temporary files
}

Step 2: Scheduling the Action

Next, you need to schedule your action. WordPress provides several hooks for scheduling events: wp_schedule_event, wp_schedule_single_event, and wp_cron_schedules for custom intervals.

To schedule your delete_temp_files function to run daily, you might add:

if (!wp_next_scheduled('delete_temp_files')) {
    wp_schedule_event(time(), 'daily', 'delete_temp_files');
}

Place this code in your functions.php file or custom plugin.

Step 3: Hooking the Function

Now, hook your custom function to a custom action:

add_action('delete_temp_files', 'delete_temp_files');

Step 4: Creating Custom Intervals

If the default hourly, twicedaily, and daily intervals don't fit your needs, you can create a custom interval using the cron_schedules filter:

add_filter('cron_schedules', 'custom_cron_schedule');

function custom_cron_schedule($schedules) {
    $schedules['every_three_hours'] = array(
        'interval' => 10800, // Time in seconds
        'display'  => __('Every Three Hours'),
    );
    return $schedules;
}

Then schedule your event using this custom interval:

wp_schedule_event(time(), 'every_three_hours', 'delete_temp_files');

Step 5: Testing and Debugging

To ensure your scheduled event works as intended, you can use plugins like WP Crontrol which allow you to view and manage scheduled cron jobs in your WordPress admin.

Step 6: Ensuring WP Cron's Reliability

For low-traffic sites, consider triggering WP Cron externally using a system cron job or a third-party service to ensure your scheduled tasks run on time. Read more on how to ensure WP Cron runs reliably.