1

I have a function to send user data to a google sheet whenever the user's profile gets updated:

add_action('profile_update','send_user_data_to_google_sheet')
function send_user_data_to_google_sheet(){
...
}

It works well except that I can feel that it apparently takes longer when users update their profiles because it has to wait for the data to be sent.

Is there a way to execute the hook asynchronously so it won't affect user's experience?

2
  • 1
    There are a few async / background task implementations for WordPress out there. I think they generally work by putting the job on a queue that's picked up by a non-web task or scheduling an action for a future wp_cron job to do. I haven't used one myself to recommend it sorry.
    – Rup
    Aug 4 at 11:12
  • 3
    Note that unless you've told your users you are sending their data to Google, this would be illegal in many countries, especially if done without their knowledge or permission, and almost certainly if those users are considered children or below the age of 13
    – Tom J Nowell
    Aug 4 at 12:18

1 Answer 1

6

Yes, that's what the WP Cron system does. It will fire an action/hook as close to a requested time as it can, and can do it once or multiple times.

You would still have a hook that runs on profile_update but it wouldn't send data to google spreadsheets, rather it would schedule a cron job that executes an action, and you would send that data on that action.

Note though that you will need to check if the cron job has been scheduled already or not to avoid duplication, and you will need to give it everything it needs to do its job as it will not be the same request ( any variables/GET/POST/FILES/etc will not be accessible, new request, blanks slate ).

For information and examples of WP Cron, refer to the official plugin handbook on the WP developers site

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.