WordPress Cron is one of the most useful features that you’ll want to learn and understand if, like me, you spend a great deal of time working with WordPress.
Being able to run certain functions on a tight schedule is essential for any CMS and WordPress has a set of functions which help make this process very simple and almost effortless.
In this article I will cover the following WordPress Cron features:You are probably familiar with the term ‘Cron’ as it relates to the time-based scheduler in Unix systems and although WordPress’ Cron is different; the main idea behind it is the same.
Some examples of how WordPress is using it’s Cron system internally is checking for theme and plugin updates and even checking if there are posts ready to be published.
If you are familiar with Unix’s Cron, you probably think that WordPress’ Cron is always on the lookout for new tasks and running them as they come. This is far from the truth and I’ll explain why shortly.
WordPress’ Cron runs when a page is loaded, whether it’s a front-end or back-end page. In other words, when a page is loaded on your website, WordPress will check if there are any tasks or events that need to run and execute them. If you are thinking this is not ideal, you are absolutely right.
If you happen to have a website that doesn’t get too much traffic and you have a task that needs to be executed at a precise time, WordPress will not know the task is due until someone visits your website. Even if it happens to be a search engine bot crawling your website.
There are two flavors of Cron events that you can schedule with a few lines of code:
Scheduling a recurring event requires that you create a custom ‘Action’ which must also be registered with Cron. Once the Cron runs, the function attached to the custom ‘Action’ you created earlier is executed.
Let’s take a look at the following example where we are going to be deleting post revisions on a daily basis.
First we create our custom ‘Action’ which will have attached to it the function we want to run when the hook is called by Cron.
<span><span><?php </span></span><span><span>// delete_post_revisions will be call when the Cron is executed </span></span><span><span>add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); </span></span><span> </span><span><span>// This function will run once the 'delete_post_revisions' is called </span></span><span><span>function delete_all_post_revisions() { </span></span><span> </span><span> <span>$args = array( </span></span><span> <span>'post_type' => 'post', </span></span><span> <span>'posts_per_page' => -1, </span></span><span> <span>// We don't need anything else other than the Post IDs </span></span><span> <span>'fields' => 'ids', </span></span><span> <span>'cache_results' => false, </span></span><span> <span>'no_found_rows' => true </span></span><span> <span>); </span></span><span> </span><span> <span>$posts = new WP_Query( $args ); </span></span><span> </span><span> <span>// Cycle through each Post ID </span></span><span> <span>foreach( (array)$posts->posts as $post_id ) { </span></span><span> </span><span> <span>// Check for possible revisions </span></span><span> <span>$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); </span></span><span> </span><span> <span>// If we got some revisions back from wp_get_post_revisions </span></span><span> <span>if( is_array( $revisions ) && count( $revisions ) >= 1 ) { </span></span><span> </span><span> <span>foreach( $revisions as $revision_id ) { </span></span><span> </span><span> <span>// Do a final check on the Revisions </span></span><span> <span>if( wp_is_post_revision( $revision_id ) ) { </span></span><span> <span>// Delete the actual post revision </span></span><span> <span>wp_delete_post_revision( $revision_id); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span><span>}</span></span>
For scheduling the recurring event we make use of the wp_schedule_event( $timestamp, $recurrence, $hook, $args ) function which takes 4 arguments:
First we make sure the event has not been scheduled before and if it hasn’t, we go ahead and schedule it.
<span><span><?php </span></span><span><span>// Make sure this event hasn't been scheduled </span></span><span><span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span><span>}</span></span>
Note that you can also add tie this snippet of code to an action. If you are a plugin writer, you could set up the scheduled event to run the first time the plugin options page is visited. For a much simpler example, we are going to tie it to WordPress’ init action.
<span><span><?php </span></span><span><span>// Add function to register event to WordPress init </span></span><span><span>add_action( 'init', 'register_daily_revision_delete_event'); </span></span><span> </span><span><span>// Function which will register the event </span></span><span><span>function register_daily_revision_delete_event() { </span></span><span> <span>// Make sure this event hasn't been scheduled </span></span><span> <span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span> <span>} </span></span><span><span>}</span></span>
Now that you know how to schedule recurring events, let’s take a look at creating a single event which will never run again until it is rescheduled.
Just as its name suggests, a single event is one that runs once and then it stops. This single event can still be rescheduled again if needed.
The concept behind it is the same as the recurring events. First you register a custom hook which is called by Cron when it runs on the server. Once Cron calls the hook, its function is executed and that’s basically how you get things done.
As an example, we are going to be setting an expiration date for posts. Posts will expire 30 days after being published. We are going to be hooking into the publish_post so that we can schedule our single event as soon as the post is published and count down begins.
Setting up the function which will delete the post after 30 days.
<span><span><?php </span></span><span><span>// delete_post_revisions will be call when the Cron is executed </span></span><span><span>add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); </span></span><span> </span><span><span>// This function will run once the 'delete_post_revisions' is called </span></span><span><span>function delete_all_post_revisions() { </span></span><span> </span><span> <span>$args = array( </span></span><span> <span>'post_type' => 'post', </span></span><span> <span>'posts_per_page' => -1, </span></span><span> <span>// We don't need anything else other than the Post IDs </span></span><span> <span>'fields' => 'ids', </span></span><span> <span>'cache_results' => false, </span></span><span> <span>'no_found_rows' => true </span></span><span> <span>); </span></span><span> </span><span> <span>$posts = new WP_Query( $args ); </span></span><span> </span><span> <span>// Cycle through each Post ID </span></span><span> <span>foreach( (array)$posts->posts as $post_id ) { </span></span><span> </span><span> <span>// Check for possible revisions </span></span><span> <span>$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); </span></span><span> </span><span> <span>// If we got some revisions back from wp_get_post_revisions </span></span><span> <span>if( is_array( $revisions ) && count( $revisions ) >= 1 ) { </span></span><span> </span><span> <span>foreach( $revisions as $revision_id ) { </span></span><span> </span><span> <span>// Do a final check on the Revisions </span></span><span> <span>if( wp_is_post_revision( $revision_id ) ) { </span></span><span> <span>// Delete the actual post revision </span></span><span> <span>wp_delete_post_revision( $revision_id); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span><span>}</span></span>
Pretty simple, right? Now we need to schedule the event once the post is actually published. In order to accomplish this task we need to use the wp_schedule_single_event( $timestamp, $hook, $args ) function which takes 3 arguments.
Here is quick look at how all this actions and hooks are put together.
<span><span><?php </span></span><span><span>// Make sure this event hasn't been scheduled </span></span><span><span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span><span>}</span></span>
We are using some time constants that WordPress has in place to make our lives easier. For more information on these constants, you can go to “Using Time Constants“, but here is a quick overview:
Now that you know how to schedule recurring and single events, it’s also going to be useful to know how to un-schedule these events.
You might be wondering, why would you want to un-schedule events? There is a good reason, particularly if you include some sort schedule events in your plugins.
Crons are stored on the wp_options table and by simply deactivating and deleting your plugin. WordPress will still try to run your events even though said plugin is no longer available. Having said that, please make sure you un-schedule events properly within your plugin or custom implementation.
Un-scheduling Cron events is relatively easy, all you need to know is the name of the hook and when is the next scheduled time that particular Cron is supposed to run. We are going to be using wp_next_scheduled() to find when the next occurrence will take place and only then we can un-schedule it using wp_unschedule_event().
Considering our first example, we would un-schedule the event the following way.
<span><span><?php </span></span><span><span>// Add function to register event to WordPress init </span></span><span><span>add_action( 'init', 'register_daily_revision_delete_event'); </span></span><span> </span><span><span>// Function which will register the event </span></span><span><span>function register_daily_revision_delete_event() { </span></span><span> <span>// Make sure this event hasn't been scheduled </span></span><span> <span>if( !wp_next_scheduled( 'delete_post_revisions' ) ) { </span></span><span> <span>// Schedule the event </span></span><span> <span>wp_schedule_event( time(), 'daily', 'delete_post_revisions' ); </span></span><span> <span>} </span></span><span><span>}</span></span>
It is possible to set custom Cron intervals which you can use when scheduling events using Cron. To do so, we just need to hook into the cron_schedules filter and add our own. Let’s take a look at adding a custom interval set to run every 10 minutes.
<span><span><?php </span></span><span><span>// delete_post_revisions will be call when the Cron is executed </span></span><span><span>add_action( 'delete_post_revisions', 'delete_all_post_revisions' ); </span></span><span> </span><span><span>// This function will run once the 'delete_post_revisions' is called </span></span><span><span>function delete_all_post_revisions() { </span></span><span> </span><span> <span>$args = array( </span></span><span> <span>'post_type' => 'post', </span></span><span> <span>'posts_per_page' => -1, </span></span><span> <span>// We don't need anything else other than the Post IDs </span></span><span> <span>'fields' => 'ids', </span></span><span> <span>'cache_results' => false, </span></span><span> <span>'no_found_rows' => true </span></span><span> <span>); </span></span><span> </span><span> <span>$posts = new WP_Query( $args ); </span></span><span> </span><span> <span>// Cycle through each Post ID </span></span><span> <span>foreach( (array)$posts->posts as $post_id ) { </span></span><span> </span><span> <span>// Check for possible revisions </span></span><span> <span>$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) ); </span></span><span> </span><span> <span>// If we got some revisions back from wp_get_post_revisions </span></span><span> <span>if( is_array( $revisions ) && count( $revisions ) >= 1 ) { </span></span><span> </span><span> <span>foreach( $revisions as $revision_id ) { </span></span><span> </span><span> <span>// Do a final check on the Revisions </span></span><span> <span>if( wp_is_post_revision( $revision_id ) ) { </span></span><span> <span>// Delete the actual post revision </span></span><span> <span>wp_delete_post_revision( $revision_id); </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span> <span>} </span></span><span><span>}</span></span>
Using WordPress’ Cron couldn’t be any easier and it is a very nice and interesting tool which is sure to help you make your plugin more robust. Learning all these functions and putting them into practice with real world applications is the best way to master WordPress’ Cron for scheduling events.
Both functions are used to schedule events in WordPress. The wp_schedule_event function is used to schedule a recurring event, meaning it will run at regular intervals that you specify, such as hourly, daily, or twice daily. On the other hand, wp_schedule_single_event is used to schedule a one-time event that will run at a specific time in the future. It’s important to choose the right function based on whether you want your event to run once or repeatedly.
There could be several reasons why your WordPress Cron job is not working. One common issue is a problem with the server’s time settings. If the server’s time is not correctly set, it can cause scheduling issues. Another possible issue is a conflict with a plugin or theme. Some plugins or themes may interfere with the WordPress Cron system, causing it to malfunction. It’s also possible that there’s an error in your code. Make sure to thoroughly test your code and check your server settings if you’re having trouble with WordPress Cron jobs.
There are several ways to test if your WordPress Cron job is working. One method is to use a plugin like WP Crontrol, which allows you to view and control what’s happening in the WP-Cron system. Another method is to use debugging tools. By enabling WP_DEBUG in your wp-config.php file, you can see any errors that occur when your Cron job runs. You can also use the error_log function in PHP to log any errors to a file.
Yes, you can schedule a WordPress Cron job to run at specific times. The wp_schedule_event function allows you to specify the time when the event should first occur, and the interval at which it should recur. The wp_schedule_single_event function allows you to specify the exact time when the event should occur.
You can unschedule a WordPress Cron event using the wp_unschedule_event function. This function requires two parameters: the timestamp of the event and the action hook to the function you want to unschedule. Once you call this function, the specified event will no longer occur.
A WordPress Cron action hook is a unique identifier for your Cron event. When you schedule an event, you associate it with an action hook. Then, you can attach functions to this action hook, and they will be executed when the event runs. This allows you to perform specific actions at specific times.
Yes, you can use WordPress Cron to schedule posts. WordPress itself uses Cron jobs to handle scheduled posts. When you set a post to be published at a future date, WordPress schedules a Cron job to publish the post at the specified time.
You can view all scheduled WordPress Cron jobs using a plugin like WP Crontrol. This plugin provides a user-friendly interface where you can see all the scheduled events, their intervals, and their next run times. You can also use it to add, edit, or delete Cron jobs.
Yes, you can run a WordPress Cron job manually. You can do this using a plugin like WP Crontrol, which allows you to run any Cron event immediately. This can be useful for testing and debugging purposes.
A WordPress Cron job is a pseudo-Cron job. It’s not a real Cron job because it doesn’t run at the server level. Instead, it runs when a page is loaded on your WordPress site. A real Cron job, on the other hand, is a task scheduled at the server level. It runs at specific times, regardless of whether anyone visits your site. While WordPress Cron jobs are easier to set up and use, real Cron jobs can be more reliable and precise.
The above is the detailed content of Mastering WordPress Cron for Scheduling Events. For more information, please follow other related articles on the PHP Chinese website!