add_action to wp cron?

Basically every page load looks to see if there is anything scheduled to run, so by that logic the cron is checked and can possibly run on every page load.

I can only presume you want to schedule something to run every so often. If that’s the case you need to look at wp_schedule_event()

Below is the code to get some code to run ever hour:

add_action('my_hourly_event', 'do_this_hourly');

// The action will trigger when someone visits your WordPress site
function my_activation() {
    if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
        wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
    }
}
add_action('wp', 'my_activation');

function do_this_hourly() {
    // do something every hour
}

If you want to fire your own code when someone else’s cron has run then you need to tie into their action that is fired. So lets take the above code is someone else’s plugin and you want to fire your code every time theirs is ran.

Well they have created an action like this:

add_action('my_hourly_event', 'do_this_hourly');

so all you need to do is piggy back your function onto this:

add_action('my_hourly_event', 'my_flush_function');
function my_flush_function() {
    // Do your code here
}

Leave a Comment