Webprogramo

How to schedule recurring events in WordPress.

I am sorry for the long introduction about Recurring Events in WordPress ='(, there is no way to do it shorter, so ¯\_(ツ)_/¯.

WordPress has a function to execute a recurring task with a defined amount of time, this means, you can set a scheduled event to be run every hour, day, week, month, year, etc.

But, do not be so happy =(, Why? Let’s talk about how WordPress Cron works; First, we have to make it a difference between what the WordPress Cron service is and the built-in server cron:

The built-in server cron is a function which is executed by the server operative system automatically at a given time. Instead, the WordPress Cron is a service that WordPress runs when it loads. So, the scheduled event can not be executed if no one runs WordPress by any means (Call a post, page, etc.). If you want to check, the file responsible of WordPress Cron is wp-cron.php in your WordPress installation root directory.

So, yes! now, you know that if no one calls a post, the home page, a page, etc., on your WordPress installation at your scheduled event time, then, your event will be executed in an out of time basis.

If you are OK with that, let’s talk about how to create Recurring Events in WordPress.

Let’s think we have created a plugin, and it is going to pull information from a RESTful service repository somewhere in this lovely world, every week. So, we need to set the scheduled event in our plugin activation hook and remove it in our plugin deactivation hook (See Activation and Deactivation Hooks), to do it, we just write this code:

// Here we register our plugin "on activation function". WordPress runs it when the user activates your plugin
register_activation_hook(__FILE__, 'on_plugin_activation');
function on_plugin_activation() {
    // First, we need to check if the schedule event is not already created, then we create it.
    if( ! wp_get_schedule( 'scheduled_api_pulling' ) ) { // "scheduled_api_pulling" 
        /**
        * Here we schedule our event in a weekly basis.
        * The first parameter is the current time to start counting.
        * The second parameter is the recurring basis term, this time is 'weekly.' (I will explain latter how to create this 'weekly' term.)
        * The third parameter is our event name, and it should be unique.
        */
        
        wp_schedule_event( time(), 'weekly', 'scheduled_api_pulling' );
    }
}

// Here we register our plugin "on deactivation function". WordPress runs it when the user deactivates your plugin
register_deactivation_hook(__FILE__, 'on_plugin_deactivation');
function on_plugin_deactivation() {
    wp_clear_scheduled_hook('scheduled_api_pulling');
}

// Finally, this is the function that is going to run every week, code your magic here.
function do_api_pulling() {
    // Do you magic API pulling information here.
}

/**
* When you create a Scheduled Event, WordPress saves it as an "action", this means, you can register several functions to this action
* and WordPress will execute them all at your chosen time (weekly in this example).
* So, in this line, we register 'do_api_pulling' function to our 'scheduled_api_pulling' (our unique scheduled event name) action.
*/

add_action( 'scheduled_api_pulling', 'do_api_pulling' );

WordPress has only three recurrence terms (How often the event should reoccur). And they are: ‘hourly,’ ‘daily’ and ‘twicedaily,’ So, if you want to create a recurrence like our ‘weekly’ one, you have to register it to the WordPress supported recurrences.

To do it, you just add this code to your plugin:

function add_our_recurrence( $schedules ) {
    // Here we add our 'weekly' recurrence to the $schedules array
    $schedules['weekly'] = array(
        'interval' => 604800, // The number in second of one week
        'display' => __('Once Weekly') // Our recurrence friendly name
    );

    return $schedules;
}

// Here is the filter to add our new recurrence function
add_filter( 'cron_schedules', 'add_our_recurrence' );

if you want to know the list of WordPress created events, use this line

    echo '<pre>' . _get_cron_array() . '</pre>';

You will get an array like this one, with every WordPress scheduled events

Array
(
    /**
    * This key value is the "The Unix Epoch" time when our event should be executed.
    * You can check it in an epoch time converter site like this one https://www.epochconverter.com/
    */
    
    [1501311192] => Array
        (
            [scheduled_api_pulling] => Array // This is our registered event ID.
                (
                    [40cd75a98d70f18aada247da8b24840a] => Array
                        (
                            [schedule] => weekly
                            [args] => Array
                                (
                                )

                            [interval] => 604800
                        )

                )
        )

        // Many other WordPress built-in scheduled events.
)

Or, alternatively, you can use WP Control to check the Scheduled Events in WordPress.

And we are done! (What a long article =/ hehe).

PD: Special thanks to Ebonie Butler. She gave me the idea to create this article.