Share
What is a Cron Job?
Cron is a technology to run scheduled tasks on your server. Cron is a technical term used for commands to run on scheduled time or at regular intervals. Most web servers use it to maintain the server and run scheduled tasks.
WordPress comes with its own cron system which allows it to perform scheduled tasks. For example, checking for updates, deleting old comments from trash, etc.
Plugins can also use it to perform tasks specified by you.
In this short tutorial we are going to create a simple Cron job WordPress plugin that sends an email every hour.
Prerequisites
- Beginner PHP Skills
- Intermediate WordPress Skills
Coding Your Cron Job Plugin
- Navigate to your wp-content/plugins folder and create your plugin folder, example: saucycron.
- Next create your plugins only php file, example: saucycron.php.
- Then open saucycron.php in your favorite text editor.
Then type out your plugin header, here’s an example:
<?php
/*
Plugin Name: Saucy Cron Email
Plugin URI: https://mydigitalsauce.com
Description: Create a simple cron job. More options: https://codex.wordpress.org/Function_Reference/wp_schedule_event
Version: 1.0
Author: MyDigitalSauce
Author URI: https://mydigitalsauce.com
License: GPL2
*/
?>
Below the plugin header, lets add an action that initializes our saucycron_init_cronjob()
add_action('init', 'saucycron_init_cronjob' );
add_action('saucycron_sendmail_hook', 'saucycron_sendemail' );
/*
* Initiating the CRON job
*/
function saucycron_init_cronjob() {
if (!wp_next_scheduled('saucycron_sendmail_hook')) {
wp_schedule_event(time(), 'hourly', 'saucycron_sendmail_hook')
}
}
Lets create our send email function that will run ‘hourly’. Here’s the thing with plugin Cron jobs, they will only run after a visitor requests your site. So if you have it set to run every hour and a user visits your site 0:59 since last cron it wont run. But if a user visits your site 1:01 since last cron, it will run.
Our email saucycron_sendemail() function uses the wp_mail(); function.
/*
* Initiating the CRON job
*/
function saucycron_sendemail() {
$saucycron_admin_email = get_bloginfo('admin_email');
// in order for this to work you need a server with email configured
wp_mail($saucycron_admin_email, 'admin', 'This is an example email sent by your WordPress Saucy CRON Email plugin.');
}
Activate The Plugin
Login to your WordPress installation. Activate the plugin, then visit the front-end of your website. Now your new Saucy Cron Email plugin should of sent an email to your sites admin_email.
And it’s that simple.