6261230701_7368aa73d6_z

Why would you need to setup WordPress cron jobs ?

Cron jobs in WordPress can be set for following reasons

  1. You have a custom post type for events and you wish to archive all your old events at regular intervals
  2. Archive logs e.g. if you have some plugin which tracks user activity then you may want to archive the logs table at regular intervals
  3. If you have integrated wordpress with some external application e.g. a mailing server then you need to synchronise your mailing lists with the external server
  4. Clearing caches for certain pages

How to setup wordpress cron jobs

wp_schedule_event is the function used to set up wordpress cron jobs

Here’s a sample code to set up a cron job

The above code will execute the function wpi_some_cron_job on daily basis. Some of the other options are hourly, twicedaily

Now the question is where do we add the above code. The answer to this depends whether you want to set this up as part of your own custom plugin or this cron is just some adhoc function which you wish to execute for housekeeping purpose e.g. clearing expired transients in your wp_options table.

Here is the code to add the cron job in the activation hook of your own plugin

Here is the code to add the cron job within your functions.php

If you have added the code to the activation hook of your plugin, it needs to be deactivate once the plugin is deactivated. Here’s how you deactivate.

Debugging WordPress Cron jobs

A. Try triggering the WordPress cron engine manually by opening below URL in your browser

http://example.com/wp-cron.php?doing_wp_cron

B. Turn on WP_DEBUG on your development environment by adding below line in your wp-config.php file

C. Create some custom field for debugging purpose and set the custom field to increment every time through a cron job runs. Then check if the field gets updated.

Leave a Reply

Your email address will not be published. Required fields are marked *