Home | About | View All Posts

27 Jul 2017

How to set cron job for running specific file in wordpress

As we know cron job is generally used to trigger or running time based execution of a task or custom code script. In wordpress it can be achieved using a plugin named as “Wp Crontrol”.

This plugin gives you control over worpdress inbuilt cron job functionality.
Plugin url -

Wordpress uses inbuilt code or functionality for cron job or scheduled task for automation like plugins update, theme updates and sending email notifications. Code can viewed in the file – “wp-cron.php” which reside at the root of the wordpress installation.
The plugin “wp control” gives an overview and control the environment in the “wordpress wp-cron system. You need to create cron event and cron schedule as per your requirement using this plugin.

Please navigate Tools > Cron Events for creating and manage cron events in the admin. For time schedule creation you have to navigate Settings > Cron Schedules in the admin.

Now you have to create callback custom function for wordpress hook in the theme functions.php or you can use another plugin named as – “My Custom Functions” - for adding code in functions.php of a theme.
Plugin url -

As we know Wordpress runs an action for executing a hook. Using this basic concept we need to tell wordpress for executing our custom function when given action is called.

Following are callback function code example:

add_action( 'my_cron_hook', 'my_cron_hook_function' );
function my_cron_hook_function() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/yourfile.php");
curl_setopt($ch, CURLOPT_HEADER, 0);

Execution of the callback or event function
First create a cron schedule name eg. “One Month”, “Five Minutes”, “One Week” etc. using “wpcontrol” admin screen at – Settings > Cron Schedules. You have to enter your schedule time in seconds in the text field “Interval(seconds)”.

Now you need to create a event hook same as above hook name – “my_cron_hook” in the wpcrontrol plugin admin screen at Tools > Cron Events. You have to select your custom created schedule name in the event creation form in “Recurrence” select box option. It ensures that, your event hook would trigger as your recurrence time selection.

Testing cron execution –
Please write following code in php file(http://www.example.com/yourfile.php) that you have placed in event function.

$to = "yourname@yourdomain.com";
$subject = "Cron Schedular Testing";
$txt = "Hello, This a test for cron job in wordpress using wpcrontrol plugin.";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: othername@yourdomain.com";

Finally go at Tools > Cron Events and click at “Run Now” at your newly created hook event for manual test.
You will get an email after successful cron execution. It will ensure that your even function is working fine.

Tags :


Post a Comment