How To's Wordpress

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.

fetch-api-store-to-json.jpg

  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

Share this article

5 thoughts on “Fetch API and store to JSON file in WordPress”

  1. Isha

    Building the cron disk-write flow tonight for a small weather widget. Hoping the host cron actually fires on time.

  2. Riya

    Partner API rate limits pushed us toward scheduled fetch-to-file. Fifteen-minute cadence is our default now.

  3. Aarav

    WP cron plus write-to-disk is uglier than a queue, yet it fits shared hosting. Code samples were nearly drop-in.

  4. Daniel Torres

    Quarter-hour snapshots to a JSON file keep a flaky upstream off the hot path. Beginner recipe that survived into prod.

Leave a Reply

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