Fetch API And Store To JSON File In WordPress Every 15 Minutes

Fetch API and store to JSON file in WordPress every 15 mins.png

In this previous post we managed to fetch the endpoint and store the response in a JSON file in wordpress as a static file. We have hooked the api calls to wp_footer which can put tremendous load to server as that will get executed on every new pageload. Hence we are trying to fetch API and store to JSON file in wordPress every 15 minutes so that if the endpoint data gets changed, we ll have updated data 4 times in an hour. And we don’t have to hook the function to every pageload event. Thus offloading some bandwidth from the server.api-fetch-wordpress-every-15-mins.png

To fetch an API endpoint and store the data to a JSON file every 15 minutes in WordPress, we can use a combination of the wp_remote_get() function to fetch the data, the file_put_contents() function to write the data to a file, and the cron daemon to schedule the task to run automatically.

Let’s do this.

  1. Create a function that fetches the data from the API and writes it to a file:
function fetch_and_store_data(){
$response = wp_remote_get("https://example.com/api/endpoint");
$data = json_decode(wp_remote_retrieve_body($response));
$upload_dir = wp_upload_dir();
$file = $upload_dir["basedir"] . "/data.json";
file_put_contents($file, json_encode($data));

  1. Schedule the function to run every 15 minutes using the wp_schedule_event function :
if ( ! wp_next_scheduled( 'fetch_and_store_data_event' ) ) {
wp_schedule_event( time(), 'fifteen_minutes', 'fetch_and_store_data_event' );
  1. Add an action that runs the function on the scheduled event:
add_action( 'fetch_and_store_data_event', 'fetch_and_store_data' );

This code first creates a function called fetch_and_store_data that makes the request to the API, decodes the JSON data, gets the path to the json file and writes the data to the file. Then it uses the wp_schedule_event function to schedule the fetch_and_store_data_event to run every 15 minutes using the fifteen_minutes schedule and add_action to run the function when the event is fired.

This solution uses WordPress built-in scheduling system, and it doesn’t require any extra configuration on the server side.

It’s important to note that the script assumes that the directory the file is being written to is writable, it’s better to use a directory that you know is writable

Leave a comment

Your email address will not be published. Required fields are marked *