Created
June 9, 2020 15:30
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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