0

I have disabled cronjobs on my nginx server, as it is better to run from crontab.

define('DISABLE_WP_CRON', true);

How could I run a custom wordpress function using Crontab, once per day?

This thread seems to offer a solution but it is not explained well enough in my opinion and might pose a security risk: execute function in wordpress plugin using crontab

On another note even if I disable WP_Cron, would wp_schedule_single_event() still work? As it would be easier to implement a solution this way.

1
define('DISABLE_WP_CRON', true);

This line disables the default behaviour of WP Cron. Which is being triggered by a user that visits the site. This is bad for a couple of reasons (nobody might visit, tasks are started via apache handler instead of PHP CLI, ...).

Now, if you have disabled it, you need another way to run WP Cron. Using crontab you could add an entry like so

*/5 * * * * php /absolute/path/to/wordpress_instance/wp-cron.php

Now wp-cron.php will run every 5 minutes via PHP CLI. This way your scheduled tasks will still run.

If you disable the default cron and don't have an alternative as mentioned above, various WordPress functions may fail to execute!


If you want to run a specific task once per day, you can wp_schedule_event() with the recurrence being daily.

  • Also do you recommend hooking the wp_schedule_event to 'init' i.e. 'add_action( 'init', 'register_daily_event');' ? – Joanna Mikalai Oct 12 '18 at 13:15
  • @JoannaMikalai No. If you call wp_schedule_event multiple times, it will schedule multiple events. You can avoid this by checking via wp_next_scheduled (as shown here). I usually put this in the plugin activation hook – kero Oct 12 '18 at 16:08
  • ok but I just have a simple function that I would like to schedule. Not sure if I should create an entire plugin for that, or if there is an easier way. Perhaps some example code would be helpful. – Joanna Mikalai Oct 12 '18 at 18:02
  • The code reference has a couple of examples. You need to put this code somewhere, a plugin seems the right choice unless your change is theme specific. You can call it in the init hook, I just personally would not. You could alternatively create a function that registers this via the click of a button or similar – kero Oct 13 '18 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.