How to use wp-ajax in plugins – wp-cron?

First, consider using the new REST API instead of Admin-AJAX in your environment where JavaScript is available.

Now to answer your question: Javascript is not available for wp-cron, as these requests only run on the server and not on some interpreted HTML/javascript. So what can you do? Well, if you haven’t finished yet (or your different workload is done) just schedule another one.

whereas wp_schedule_event() used for recurring events, there is also wp_schedule_single_event() Which can be used for “not yet finished” workloads.

Let’s say you want to clean your DB daily, the workflow might look like this

  1. wp_schedule_event() daily run function clean_my_db()
  2. within clean_my_db() you create an array $tables_to_clean = ['posts', 'postmeta'], you call now wp_schedule_single_event() to run clean_my_db_table() and pass each table as an argument.
  3. clean_my_db_table('posts') Run
  4. clean_my_db_table('postemta') Run
  5. e.t.c

In short: you have a function called by wp_schedule_event() which is a recurring phenomenon. within it you decide to split the workload and run them wp_schedule_single_event() on specific dates/times.

Leave a Comment