0

I am devloping a custom plugin for woocommerce. In that plugin the functionality is like it will get all the users and send them email in every 24 hrs. So doing a work in every 24hrs even without visiting a site I think I need a cron job for that. So by googling over wordpress cron job I got wp_schedule_event function. But here I can't understand how to work with it? I mean how the function will work here? I have my custom function to get all the users and send them email but how to work that function with wp_schedule_event and how the wp_schedule_event function should be call from the plugin so that if no one even visits the site it will work silently. Any help and suggestion will be really appreciable. Thanks

NewUser
  • 12,713
  • 39
  • 142
  • 236
  • [Tooting my own horn](http://stackoverflow.com/questions/35888969/run-a-wordpress-query-every-week/35889244#35889244) :D Server cron job (non wp) will execute irregardless if your site was visited or not, whereas wp_cron depends on site visit, but once someone visits it fires. But I think it's safer to use wp_cron, than server, because if the server crashes, and you missed the timestamp, the cron won't execute (from my limited understanding of cron jobs), whereas if for wp_cron it will run the next time someone visits, even if site was down... – dingo_d Mar 18 '16 at 07:13

1 Answers1

2

You need to map your plugin function to an action, and then schedule that action to the Wordpress cron.

// ---- Schedule cron event for custom plugin function.
add_action('init', 'custom_plugin_function_event');
function custom_plugin_function_event() {
    if (wp_next_scheduled('custom_plugin_action') == false) {
        wp_schedule_event(time(), 'daily', 'custom_plugin_action');
    }
    add_action('custom_plugin_action', 'custom_plugin_function');
}

// ---- Execute custom plugin function.
function custom_plugin_function() {
    // Do something here
}

The above example is for procedural code. replace custom_plugin_function() with your plugin function's name.

Lutrov
  • 340
  • 2
  • 8
  • so this will work even no one visits the site? Because I can see you have used `init` hook and this hook needs to be run when the site is loaded. So to do that someone has to visit the site right? I want without visiting site the function should run – NewUser Mar 18 '16 at 16:38
  • No, mate. It only executes when a user visits the site (the first time). That's how WP cron works. If you want to schedule a cron event even when no-one visits a site you have to do it the good old fashioned way via Linux cron. – Lutrov Mar 18 '16 at 23:22
  • I have used that but its not working. You can check that in my other question here http://stackoverflow.com/questions/36316336/wordpress-schedule-event-not-firing-in-set-time?noredirect=1#comment60263930_36316336 – NewUser Mar 31 '16 at 10:56