In this part of this series, we are going to be introduced with Using Cron Job in WordPress and practice WP-Cron which is a fantastic way to schedule a Cron Job with WordPress. Now, there is a particular difference between regular Cron and WP-Cron. In the case of regular Cron, it runs in a specific time interval but WordPress does it in a slightly different way. Though WordPress allows you to set up a specific time interval, it won’t execute it until someone visits your website (they can be a human visitor, a search engine bot or you). So, in order to be run a WP-Cron the specified time must have to be passed and at the same time, someone must visit your website.
Using Cron Job in WordPress – Schedule Events With WP-Cron:
To get started with WP-Cron, we will create a simple cron job which will write to file in every 1 hour.
<?php /* * Plugin Name: WP Cron Test * Plugin URI: http://zubaer.com * Description: WP Cron Job Practice * Version: 1.0.0 * Author: Md. Zubaer Ahammed * Author URI: http://zubaer.com */ add_action('init', function() { if(!wp_next_scheduled('wptutshub_cron_hook_hourly')) { wp_schedule_event(time(), 'hourly', 'wptutshub_cron_hook_hourly'); } }); add_action('wptutshub_cron_hook_hourly', function() { $current_time = time(); $file = WP_PLUGIN_DIR."/wpcron/demofile.txt"; $myfile = fopen($file, "w") or die("Unable to open file!"); $txt = "This string was written (hourly) at $current_time.\n"; fwrite($myfile, $txt); fclose($myfile); }); ?>
Explanations:
We are scheduling an event with wp_schedule_event($timestamp, $recurrence, $hook, $args) function which takes three arguments:
- $timestamp (required): we have used the current time with time() function.
- $recurrence (required): How often it will reoccur. WordPress supports three default value for it (We shall create custom recurrence shortly): hourly, twicedaily, daily
- $hook (required): Action hook to execute
- $args (optional): Optional arguments to pass to the hook function(s).
But we cannot just schedule a cron job and get done with it. Because it will register it on every page load (as we attached it with ‘init‘ hook). So, we are checking if it’s not scheduled for next already with wp_next_scheduled() function which takes the hook as a parameter. We are writing current time to a file named ‘demofile.txt‘ in our plugins root directory. We have used time() function as our $timestamp parameter. So, if we load any page (such as reload WP Dashboard or visit a web page), this Cron will write to that file.
Creating Custom Time Interval:
So, alongside the default time intervals (hourly, twicedaily, daily), you may want to create your own custom time interval. Let's say we want to write to the file in every single minute. So, our code will be like below:
add_filter('cron_schedules', function($schedules) { $schedules['one-minute'] = array( 'interval' => 60, 'display' => 'Every Single Minute' ); return $schedules; });
Explanations: Here we are attaching a new interval with ‘cron_schedules‘ filter. An array ($schedules) containing all default intervals will be passed to the closure function to which we can add our own time interval. The name can be anything but the main thing is ‘interval‘ key which denotes the amount of time in seconds. And ‘display‘ is only for reading purposes if you want to read this interval later as an option.
Now, we have previously scheduled a Cron which runs hourly and writes to the file. If we don’t unschedule it, it will run eternally in every single hour. So, let’s see how to unschedule a Cron Job with WordPress.
Unschedule a Cron Job:
$time = wp_next_scheduled('wptutshub_cron_hook_hourly'); wp_unschedule_event($time, 'wptutshub_cron_hook_hourly');
Explanations:
First we are getting the time of the next scheduled event or when the event with ‘wptutshub_cron_hook_hourly’ is going to be run next. Then we unschedule it with ‘wp_unschedule_event()’ function which takes two parameters $time and $hook of the scheduled event/cron job.
So, Our Final Code will look like below:
<?php /* * Plugin Name: WP Cron Test * Plugin URI: http://zubaer.com * Description: WP Cron Job Practice * Version: 1.0.0 * Author: Md. Zubaer Ahammed * Author URI: http://zubaer.com */ /** * Hook it with 'init' hook (WordPress has fully loaded but it's hasn't sent any headers yet.) */ add_action('init', function() { //Unschedule an laready scheduled event which we did with 'hourly' time interval in the beginning of the article. $time = wp_next_scheduled('wptutshub_cron_hook_hourly'); wp_unschedule_event($time, 'wptutshub_cron_hook_hourly'); //Schedule an event which will run in every single minute. if(!wp_next_scheduled('wptutshub_cron_hook_minute')) { wp_schedule_event(time(), 'one-minute', 'wptutshub_cron_hook_minute'); } }); /** * Defining our hook. */ add_action('wptutshub_cron_hook_minute', function() { $current_time = time(); $file = WP_PLUGIN_DIR."/wpcron/demofile.txt"; $myfile = fopen($file, "a+") or die("Unable to open file!"); $txt = "This string was written (per minute) at $current_time.\n"; fwrite($myfile, $txt); fclose($myfile); }); /** * Create custom schedule or time interval. */ add_filter('cron_schedules', function($schedules) { $schedules['one-minute'] = array( 'interval' => 60, 'display' => 'Every Single Minute' ); return $schedules; }); ?>
In the next part this article we will see more about WP-Cron such as how to handle it from options page, displaying single events, scheduling a single event, etc. Also, you can contact me directly regarding any help.
2 Comments