Skip to content

Instantly share code, notes, and snippets.

@wpscholar
Created June 9, 2020 15:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpscholar/96638f4bc5c499eab691d93986be8546 to your computer and use it in GitHub Desktop.
Save wpscholar/96638f4bc5c499eab691d93986be8546 to your computer and use it in GitHub Desktop.
An example of how to make an external API call in WordPress and cache the response.
<?php
$cache_key = 'my_api_call_response';
$response = get_transient( $cache_key );
if ( ! $response ) {
$response = wp_remote_get('https://example.com/api/v1/endpoint');
$status_code = (int) wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( 200 === $status_code && $data ) {
// Process data
set_transient( $cache_key, $response, HOUR_IN_SECONDS );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment