Fetch API and store to JSON file in WordPress

fetch-api-store-to-json.jpg

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 

1 comment

Leave a comment

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