Fetch API and store to JSON file in WordPress
At times when we have limited access to an API endpoint where the get calls are restricted to a certain number of times, yet we want to show data from API every time a user hits our page. And when we have to do all this using WordPress as a platform, there is an easy peasy method available that simplifies all this.

function cacheTheEndpoint(){
$url = 'https://apiendpoint.com/xxx/xx/';
$response = wp_remote_get($url);
$responseData = json_encode($response);
file_put_contents('dumpedData.json', $responseData);
}
add_action('wp_footer', 'cacheTheEndpoint');
You can then access the file in your root directory and parse the data from there instead of the endpoint. But problem is that this will get triggered every time a user loads the website. Which fails the entire purpose of generating a local JSON file. Well, we can solve that as well. Check out my next post.
Read this if you want to remove HTML comments in VS Code without extension
Related: Fetch API And Store To JSON File In WordPress Every 15 Minutes
Related: Move All WordPress Posts To Trash

[…] this previous post we managed to fetch the endpoint and store the response in a JSON file in wordpress as a static […]
Building the cron disk-write flow tonight for a small weather widget. Hoping the host cron actually fires on time.
Partner API rate limits pushed us toward scheduled fetch-to-file. Fifteen-minute cadence is our default now.
WP cron plus write-to-disk is uglier than a queue, yet it fits shared hosting. Code samples were nearly drop-in.
Quarter-hour snapshots to a JSON file keep a flaky upstream off the hot path. Beginner recipe that survived into prod.