In this article, I will explain you about the fundamentals of the WordPress Cron Job.Cron is basically a task scheduler that periodically on a given schedule.
WordPress Cron API is quite easy to understand but before you dive into it, make sure you’re familiar with WordPress action and filter hooks.WordPress has a own Cron API which allows us to schedule events and to execute task for a future purpose.
Let’s take a look into code snippet.
Here, we have used two functions for task scheduling and are wp_schedule_event and wp_next_scheduled.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | add_action( 'my_cron_hook', 'my_cron_function' ); if ( ! wp_next_scheduled('my_cron_hook') ) { //condition to makes sure that the task is not re-created if it already exists wp_schedule_event( time(), 'hourly', 'my_cron_hook' ); } } add_action( 'init', 'schedule_my_cron' ); function my_cron_function() { $my_post = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', ); wp_insert_post($my_post); } |
You just need to place above code into the functions.php
file and yes here i have insert a post but you can write any code or functionality you want to execute while cron runs.
If you don’t want the automatic cron to run while you’re debugging, then add following line of code into your wp-config.php file
1 2 3 | define('DISABLE_WP_CRON', true); |
You may also like:
WordPress Shortcode for Bootstrap Alert box
Disable updates for specific plugin in WordPress
Introduction to Transient API in WordPress
That’s all about to adding a cron job.Thank you for reading and hope you enjoyed it.
Feel free to share your thoughts! Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (1)