Easiest Implementation of WordPress Background Processing

WordPress sites are not just used only for publishing content but also can be used for complex applications like complex form processing, CRM, email marketing, e-commerce, and what’s not. Sometimes, You may run some tasks which can often be resource-intensive or time-consuming. For example: After submitting a frontend form, You may send the data to Google Sheet, send data to your external marketing services, send emails and say a few more. Each API calls will take its own time and if you want to process everything it may take more than 30 seconds and it’s not a good idea to make the end-user wait for showing the success message. (We implemented a similar mechanism for Fluent Forms)

For my case, I was building an action block for FluentCRM where users can send data to a remote server, and at a time, It may call 100s of API calls. So it will be a bad idea if we just run the tasks on the same process.

So, We can just run these processes in the background and show the form success message instantly. In WordPress, There have some great libraries that you can use but in this tutorial, we will implement a very basic background task processor.

Wrapper Function

Let’s first create a global function that will queue our process and give us an easy way to run our long queue processes:

Here we have created an easy API to run our background processes. You can copy the code and replace the “my_custom_” with your own plugin prefix.

Usage

Say, You have a time consuming function for example:

<?php

function myTimeConsumingFunction($data) {
    // send api call 1
    
    // send api call 2
    
    // send email
    
    // do other things
}

myTimeConsumingFunction(['api_calls' => 10]);

Now we can convert this as bellow which will run this function in the background:

my_custom_queue_on_background('my_callback_run_time_consume_func', ['api_calls' => 10]);

add_action('my_callback_run_time_consume_func', 'myTimeConsumingFunction');

That’s it. Now our my_custom_queue_on_background function will queue the process on the background and add_action(); line will catch that action and call myTimeConsumingFunction.

Example usage and logs

Footnote

In this implementation, No Database query or record is required. It will call the callback action instantly from the ajax call which will not wait for competing the task. For you basic use cases, You can use this mechanism.

This example is for showing how background processing for WordPress work and there has few libraries that you can also check

Add your first comment to this post