Fetch API And Store To JSON File In WordPress Every 15 Minutes
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.
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.
- 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));
}
- Schedule the function to run every 15 minutes using the
wp_schedule_eventfunction :
if ( ! wp_next_scheduled( 'fetch_and_store_data_event' ) ) {
wp_schedule_event( time(), 'fifteen_minutes', 'fetch_and_store_data_event' );
}
- 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.
The script assumes the target directory is writable, so point it at a directory you know the web server can write to.

Clearest interval math and hook names I found for WP scheduled fetches. Copied timing into our cron plugin settings.
Implementing the cron plus disk write tonight for a rates widget. Fingers crossed the host cron is reliable.
Fetch-to-file beats hammering a slow API on every page view. Boring pattern, happier TTFB numbers.
Thought I knew scheduled JSON snapshotting; failure retry gaps showed up here. Logger now records miss streaks.
Fifteen-minute cron fetch to disk keeps a dashboard feed alive on cheap hosting. Still running months later.