WordPress provides an excellent scheduling system known as wp_cron, which allows developers to schedule tasks to run automatically at certain intervals. This can be useful for a variety of use cases like running background tasks, sending emails, cleaning up old data, or performing any other maintenance task on a regular basis.

In this article, we will walk through how to create a WordPress plugin that utilizes the wp_cron API to schedule and run a task.

Prerequisites

Before you begin, make sure that you have the following:

  • A WordPress installation (local or live).
  • A basic understanding of WordPress plugin development.

Step 1: Set Up Your Plugin

To start, you need to create a basic plugin. Follow these steps:

  1. Create a Plugin Folder
    Inside the wp-content/plugins directory, create a folder for your plugin. Let’s call it wp-cron-example.
  2. Create the Main Plugin File
    Inside your wp-cron-example folder, create a file named wp-cron-example.php and add the following header information:
<?php
/**
 * Plugin Name: WP Cron Example
 * Plugin URI: https://yourwebsite.com/
 * Description: A simple plugin demonstrating the use of wp_cron API.
 * Version: 1.0
 * Author: Your Name
 * Author URI: https://yourwebsite.com/
 * License: GPL2
 */

// Don't allow direct access to this file
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// The plugin code will go here
PHP

This is the basic plugin structure, and it helps WordPress identify your plugin and display its details in the dashboard.

Step 2: Define the Scheduled Event

The first thing you’ll need to do is define the scheduled event. This is the task that will run at specified intervals using wp_cron.

  1. Define a Custom Function
    Add the following function inside the plugin file. This function will run when the cron job executes:
function wp_cron_example_task() {
    // This is the function that will run when wp_cron triggers
    // In this example, we'll simply log a message to the debug log
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        error_log( 'WP Cron Task Executed: ' . date( 'Y-m-d H:i:s' ) );
    }
}
PHP

This function logs a message to the WordPress debug log when it is executed. You can replace this with any logic you need for your task (e.g., sending emails, clearing old data, etc.).

  1. Hook the Task to wp_cron
    You need to hook this function into the wp_cron system so that it runs on a schedule. You can do this by using the wp_schedule_event() function.

Add the following code to your plugin:

function wp_cron_example_schedule_task() {
    // Check if the event is already scheduled to prevent multiple schedules
    if ( ! wp_next_scheduled( 'wp_cron_example_event' ) ) {
        // Schedule the event to run every hour
        wp_schedule_event( time(), 'hourly', 'wp_cron_example_event' );
    }
}

// Hook the event schedule function to WordPress 'init' action
add_action( 'init', 'wp_cron_example_schedule_task' );

// Hook the task function to the scheduled event
add_action( 'wp_cron_example_event', 'wp_cron_example_task' );
PHP

Explanation:

  • wp_next_scheduled(): Checks if the cron job is already scheduled.
  • wp_schedule_event(): Schedules the event. The parameters are:
  • time(): The timestamp for when the event should first run (using the current time).
  • 'hourly': The recurrence interval (you can use built-in intervals like hourly, twicedaily, or daily, or create custom ones).
  • 'wp_cron_example_event': A unique event name.
  • add_action( 'init', 'wp_cron_example_schedule_task' ): Ensures that the event scheduling function runs when WordPress initializes.
  • add_action( 'wp_cron_example_event', 'wp_cron_example_task' ): Hooks the task function to the scheduled event.

Step 3: Custom Intervals (Optional)

If the default intervals (hourly, twicedaily, daily) do not suit your needs, you can add custom intervals by using the cron_schedules filter.

Here’s an example of how to add a custom interval of 15 minutes:

function wp_cron_example_add_custom_intervals( $schedules ) {
    // Add a custom schedule of 15 minutes
    $schedules['every_fifteen_minutes'] = array(
        'interval' => 15 * 60, // 15 minutes in seconds
        'display'  => __( 'Every 15 Minutes' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'wp_cron_example_add_custom_intervals' );
PHP

Now, when scheduling an event, you can use 'every_fifteen_minutes' as an interval.

Step 4: Deactivating and Cleaning Up

It’s important to clean up after your plugin to ensure that scheduled events do not continue running after the plugin is deactivated.

You can do this by adding a deactivation hook to remove the scheduled event:

function wp_cron_example_deactivate() {
    // Clear the scheduled event when the plugin is deactivated
    $timestamp = wp_next_scheduled( 'wp_cron_example_event' );
    if ( $timestamp ) {
        wp_unschedule_event( $timestamp, 'wp_cron_example_event' );
    }
}
register_deactivation_hook( __FILE__, 'wp_cron_example_deactivate' );
PHP

Step 5: Testing Your Plugin

  1. Enable Debugging
    To see the output of the cron job, make sure that WordPress debugging is enabled. Add the following lines to your wp-config.php file if you haven’t already:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
PHP

This will log the output of the cron job to wp-content/debug.log.

  1. Check the Cron Job
    You can test if the cron job is working by checking the debug.log file in the wp-content directory. If everything is set up correctly, you should see a log entry each time the task runs.
  2. Run Cron Manually
    Sometimes the WordPress cron system may not trigger as expected (especially on local environments). You can trigger the cron job manually by visiting the following URL (replace your-site.com with your actual site URL):
http://your-site.com/wp-cron.php?doing_wp_cron

This will force WordPress to run all scheduled tasks.


Conclusion

By following these steps, you’ve created a WordPress plugin that uses the wp_cron API to schedule tasks to run automatically at regular intervals. WordPress’s cron system is a powerful tool for automating background tasks, and it integrates seamlessly with WordPress plugins.

In this tutorial, we’ve only scratched the surface of what wp_cron can do. You can extend this basic plugin to perform more complex tasks, such as cleaning up old data, sending periodic email notifications, or interacting with external APIs. The wp_cron system is a flexible, essential part of the WordPress ecosystem for automating maintenance and scheduled activities.