Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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