How to Automate Tasks with WordPress Cron Job
Managing a website comes with a lot of challenges, especially when your site is getting large traffic. For this reason, it is important to automate some tasks on your WordPress website. The WordPress Cron system makes scheduling and automating some jobs easy.
If you have ever scheduled a post to publish at a specific time on your website, then you have been using the WordPress Cron system.
In this guide, we will show you how to automate tasks with WordPress cron jobs. But first, let’s understand what cron means and how the WordPress Cron system works.
Content
- What is a Cron?
- WP Cron job.
- Pros and cons of WordPress Cron job.
- How to automate tasks with WordPress Cron job.
- Conclusion.
What is Cron?
Cron is simply a utility for scheduling time-based tasks. It is a UNIX utility which means it comes preinstalled on Linux-based systems as well as web servers. The task that is being scheduled or automated is known as the cron job.
The WordPress cron works quite differently than a system cron. The system or servers cron can specify the exact time a task should run. The task will run at the specified time and is not dependent on any external factor.
However, this is quite different from how WordPress cron jobs work.
WordPress Cron Job
The WordPress cron, also known as WP-Cron, is a PHP file that comes with every WordPress installation. It is usually available in the root directory of your WordPress hosting server.
WP-Cron is simply a WordPress feature for handling time-based tasks in WordPress. Tasks such as checking for updates or publishing scheduled posts utilize the WP Cron system. The tasks that are being run by WP-Cron are regarded as WordPress cron jobs.
Unlike the system cron which can run at any specified time, the WordPress cron system uses intervals. The default WordPress intervals for scheduling tasks are;
- hourly
- twice daily
- daily
- weekly
Running cron jobs in WordPress depends on page load to trigger an action. This means a task will only run when someone visits your website.
Pros and Cons of WordPress Cron Job
As we saw above, the WordPress Cron system depends on page load to run. Despite this, it also has some advantages over a real cron job.
In this section, we will present the pros and cons of WordPress cron jobs, so you can take an informed decision on whether to continue using WP-Cron or disable it and use the system cron instead.
Pros
WP Cron makes it easy for the WordPress core and other plugins to perform time-based tasks. In addition, it is relatively easy to set up a WordPress Cron job as opposed to using a real cron job that requires knowledge of Linux commands.
Also, because the WP-Cron uses intervals to schedule tasks, you can be rest assured that your task will eventually run even if the scheduled time elapses.
Unlike a real cron that specifies the exact time a task should run. If the time passes and the task fails to run, then it will not run again until you manually reschedule it.
Cons
WP-Cron will only work when a page is loaded on your website.
This can be a problem especially when your site receives low traffic and you require a task to run at regular intervals.
Let’s say you schedule a task to run at 3am and your site does not receive any traffic until 8am (which is possible for small websites).
The task initially scheduled to run at 3am will now run at 8am when a page is loaded on your website.
By scheduling tasks such as database optimization, cache clearing, and updates, you can enhance WordPress website speed and performance. Automated tasks help keep your site running smoothly, providing a better experience for your visitors.
How to Automate Tasks with WordPress Cron Job
There are a couple of ways to manage cron jobs in WordPress, such as using a WordPress cron job plugin, through WP-CLI, or manually setting them in the theme’s function.php file.
However, in this guide, we will be using a plugin to set and manage WP-Cron. There are a number of popular plugins that can be used to achieve this, but we will stick with the WP Crontrol plugin because it provides all the features needed, and it is free.
With the WP Control plugin, you can view all the cron jobs running on your website. It also lets you modify and delete cron jobs.
Also, adding a new cron event and setting new cron schedules can be achieved easily using the plugin.
To get started, you will need to install and activate the plugin on your WordPress site. Here’s a guide on how to install WordPress plugins.
After activating the plugin, proceed with the steps below.
Adding Custom Cron Interval
Earlier we mentioned that the wpcron system uses four intervals (hourly, twicedaily, daily, and weekly) for scheduling tasks, however, you can add a custom time interval for your cron events.
This can be achieved using the WP Crontrol plugin or by manually registering the schedule on your themes’ function.php file.
Using WP Crontrol Plugin to add Cron Interval
To do this, login to the admin dashboard of your WordPress site and go to Settings > Cron Schedules.
On the Cron schedule dashboard, you will find all the intervals available on your website.
Now, on the left, add the interval name. We recommend using a descriptive name that corresponds to the interval value. Also, interval names should be in lowercase and should be multiple words separated using an underscore (eg every_ten_minutes).
After that, add the interval value in seconds, i.e. for a 10 minutes interval, the value should be 600.
Next, add a display name for the interval. The name should be descriptive as well (eg Every 10 minutes).
Now, click on the ‘Add Cron Schedule’ button.
Using Code to Add Custom Time Interval
Alternatively, you can register your custom cron schedule on your themes’ function.php file. Here’s how to add it.
Firstly, connect to cPanel or access your site via FTP. Please read this guide to learn how to use FTP.
After connecting your site to Filezilla FTP, on the right, you will find your remote site files.
Now, double-click on the directory containing your site files (usually public_html).
On your site directory, double click on the wp-content folder.
Now, double click on the themes folder.
After that, double click on your current theme’s folder to open it.
Within this folder, locate and right-click on the functions.php file and then select View/edit (you will be prompted to select a text editor to open the file).
Now, add the following lines of code below to register a new Cron Schedule
add_filter( 'cron_schedules', 'example_add_cron_interval' );
function example_add_cron_interval( $schedules ) {
$schedules['five_minutes'] = array(
'interval' => 300,
'display' => esc_html__( 'Every Five Minutes' ), );
return $schedules;
}
The filter function above creates a cron schedule that runs every five minutes.
Interval values by default are in seconds, so you have to convert your desired interval to seconds and then enter the value in the interval object.
WP-Cron Events
Using the WP Control plugin, you can find all the wpcron jobs already running on your website. From the dashboard, you can modify or delete any of them. The hook names can tell whether it is a WordPress core cron job or a third-party plugin cron job.
For example, WP Cron events that begin with ‘wp_’ prefix denote that they are default WordPress cron jobs. You cannot delete this type of cron job with the WP Crontrol plugin.
To see all the cron jobs running on your website, login to the admin dashboard of your site and then click on Tools > Cron Events.
On the dashboard, you will find all the scheduled events already running on your website. The action names are the function that will run when an event is triggered.
To run a cron job, hover over the cron event and then select ‘Run Now’ located below the Hook name.
Adding Cron Event
With the WP Crontrol plugin, you can add your own cron jobs as well. However, you need to assign a function to the cron event so that WordPress knows what to do when the event is triggered.
To add a cron event, click on the Add New button under Tools > Cron Event.
Now, on the Event type, select the standard cron event option.
After that, add the hook name. The hook name should be in lowercase separated using an underscore. The naming should be descriptive such that you can tell what the cron event does from the hook name.
Next, select the next time you want the event to run. In my case, I used the ‘Run Now’ option.
After that, select the recurrence period. Recall, we created a custom interval to run every 10 minutes. Now, we will use the interval to schedule the cron event.
Now, click on the ‘Add Event’ button to add the new cron.
You can find the new cron event we created under Tools > Cron Events section. Under the Action column, you will notice that the value is None, denoting that no function has been assigned to the cron event.
To add an action hook to the cron event, you will need to create a function that tells WordPress what to do when the cron is triggered. Here’s how to do it.
Adding an Action Hook to Cron Event
Open your themes’ function.php file (steps to open this file can be found in the add cron schedule section above).
Now, add the line of code below to register the cron event.
add_action( 'gt_send_email_to_admin', 'gt_email_cron' );
The first parameter is the hook name we assigned when creating the cron event. In my case, the value is ‘gt_send_email_to_admin’. Then the second parameter is the function that tells WordPress the action to take.
The next step is to create the function that will run whenever you trigger the cron event. For this example, we will use the wp_mail() function to send an email message. Paste the code below on your themes’ function.php file.
function gt_email_cron() {
wp_mail( '[email protected]', 'Testing New Cron Event', 'Wow!!! It works. Feels good!' );
}
Ensure you replace [email protected] with an actual email address you can access.
Save and upload the file after adding the code snippets above.
Testing Custom Cron Events
Now that we have successfully added a cron event and assigned the function that will run whenever it is triggered, the next line of action is to test the WordPress cron job.
On your WordPress admin dashboard, go to Tools > Cron Events.
Now, locate the new cron event we created. Notice that there is now a function under the Action column.
Hover over the new cron event and then select Run Now. You should see a success message like the one below.
Now, check your email, you should receive an email from WordPress with the content we specified in the function.
Check your spam folder if the email is not available in your inbox.
Modifying Cron Events
You can edit WordPress cron jobs directly from the WP Crontrol dashboard. Simply hover over the cron event and then click Edit.
Side Note: WordPress core, as well as third-party plugins, rely on their cron jobs to work properly. Modifying their values might affect your website performance.
You can change the cron schedule for your custom cron events or modify the hook name.
Click on update Event after making any change.
Deleting WordPress Cron Jobs
If you wish to delete a cron event, you can do so from the WP Crontrol dashboard. However, you should be careful as deleting a plugin’s cron job may affect how the plugin works on your website.
To delete a cron event, hover over the Hook name and then select Delete.
Note that there is no Confirm Delete option, so you should be sure you want to delete the cron event before proceeding.
You will get a notification that the cron event has been deleted as seen above.
Conclusion
WordPress Cron is a very useful tool for website owners. It helps automate boring and repetitive tasks, thereby giving the site owner ample time to be more productive.
In this guide, we explained what Cron means in detail and how the WordPress Cron system works. Also, we shared a beginner-friendly guide on how to automate tasks using cron jobs.
If you found this article helpful, kindly share it with others.
Automating tasks with WordPress cron jobs can greatly enhance your site’s efficiency and free up your time for other important activities. Whenever you need assistance or run into challenges, don’t hesitate to seek Help with WordPress Issues to keep your website running optimally