How to use wp-ajax in wp-cron

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

Now to answer your question: JavaScript isn’t available for wp-cron, as these requested solely run on the server and not on some interpreted HTML/JavaScript. So what can you do? Well, just schedule another event if you didn’t finish yet (or your separated workload is done).

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

Say you want to clean your db daily, a workflow could look like this

  1. wp_schedule_event() to dail run function clean_my_db()
  2. Within clean_my_db() you create an array $tables_to_clean = ['posts', 'postmeta']. Now you call wp_schedule_single_event() to run clean_my_db_table() and pass each of the tables as argument.
  3. clean_my_db_table('posts') runs
  4. clean_my_db_table('postemta') runs
  5. etc

To summarize: You have one function called by wp_schedule_event() which is a recurring event. Within that you decide to split workloads and run them via wp_schedule_single_event() at specific dates/times.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)