Fetching external data with the WordPress HTTP API and transient cache
WordPress includes its own HTTP API that wraps PHP’s cURL and streams into a consistent interface. Using it instead of raw cURL means your code works correctly across different hosting environments without manual capability checks.
Problem: How do you make HTTP requests to an external API in WordPress without using raw cURL, and how do you avoid hitting rate limits on every page load?
Solution: The example below fetches data from a public JSON endpoint, caches it with a transient, and returns a decoded array:
function get_remote_posts() {
$cache_key = 'remote_posts_cache';
$data = get_transient( $cache_key );
if ( false !== $data ) {
return $data;
}
$response = wp_remote_get( 'https://jsonplaceholder.typicode.com/posts', [
'timeout' => 10,
] );
if ( is_wp_error( $response ) ) {
return [];
}
$code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $code ) {
return [];
}
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );
if ( ! is_array( $data ) ) {
return [];
}
set_transient( $cache_key, $data, HOUR_IN_SECONDS );
return $data;
}
For POST requests, use wp_remote_post() with a body argument:
$response = wp_remote_post( 'https://example.com/api/endpoint', [
'timeout' => 15,
'headers' => [ 'Content-Type' => 'application/json' ],
'body' => wp_json_encode( [ 'key' => 'value' ] ),
] );
NOTE: Always check is_wp_error() before reading the response. Use set_transient() to cache external responses — hitting a third-party API on every page load will slow your site and may trigger rate limits.