Key Takeaways
- WordPress Cron is a set of functions that enables scheduling of tasks on a WordPress site, running when a page is loaded. It is different from Unix’s Cron as it is not always on the lookout for new tasks, instead, it executes tasks upon page loading.
- There are two types of Cron events that can be scheduled: single events, which run once and never again until rescheduled, and recurring events, which run on a set schedule indefinitely. Both types require the creation of a custom ‘Action’ which must be registered with Cron.
- Un-scheduling events is essential, especially when using plugins, as WordPress will continue to attempt to run events even after a plugin is deactivated or deleted. To un-schedule an event, one needs to know the name of the hook and the next scheduled time for the Cron run.
- Custom Cron intervals can be set by hooking into the cron_schedules filter and adding a custom interval. This can be utilized when scheduling events using Cron.
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:- How is WordPress Cron different than your normal Cron
- Scheduling a recurring event
- Scheduling a single event
- Un-scheduling an event
- Specifying custom Cron intervals
What is Cron?
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.
How is WordPress Cron Different?
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.
Scheduling Events with Cron
There are two flavors of Cron events that you can schedule with a few lines of code:
- Single events – run only once and never again until it is rescheduled again.
- Recurring events – run on a schedule and is set to re-occur indefinitely using a time interval.
Scheduling a Recurring Event
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:
- $timestamp — (integer) (required) The first time that you want the event to occur. This must be in a UNIX timestamp format. WP cron uses UTC/GMT time, not local time. Use time(), which is always GMT in WordPress. (current_time( ‘timestamp’ ) is local time in WordPress.)
- $recurrence — (string) (required) How often the event should reoccur. Valid values are ‘hourly‘, ‘twicedaily‘ and ‘daily‘. We’ll see how to create our own time intervals later.
- $hook — (string) (required) The name of an action hook to execute.
- $args — (array) (optional) Arguments to pass to the hook function(s).
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.
Scheduling a Single Event
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.
- $timestamp — (integer) (required) The time you want the event to occur. This must be in a UNIX timestamp format.
- $hook — (string) (required) The name of an action hook to execute.
- $args — (array) (optional) Arguments to pass to the hook function.
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:
- MINUTE_IN_SECONDS = 60 (seconds)
- HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS
- DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS
- WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS
- YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS
Un-scheduling Events
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>
Customizing Cron Intervals
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>
Conclusion
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.
Frequently Asked Questions about Mastering WordPress Cron
What is the difference between wp_schedule_event and wp_schedule_single_event?
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.
Why is my WordPress Cron job not working?
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.
How can I test if my WordPress Cron job is working?
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.
Can I schedule a WordPress Cron job to run at specific times?
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.
How can I unschedule a WordPress Cron event?
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.
What is a WordPress Cron action hook?
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.
Can I use WordPress Cron to schedule posts?
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.
How can I view all scheduled WordPress Cron jobs?
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.
Can I run a WordPress Cron job manually?
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.
What is the difference between a WordPress Cron job and a real Cron job?
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.
