WordPress HTTP API: wp_remote_get() and wp_remote_post() best practices
The WordPress HTTP API (wp_remote_get(), wp_remote_post(), wp_remote_request()) wraps the transport (cURL or PHP streams) in one interface with the same arguments and the same response format everywhere. Used carelessly it gives silent failures, hung pages and API rate limits; used well it needs four habits: check errors, set timeouts, cache responses, and keep remote calls out of the page render.
Problem: Remote requests are made with the defaults and their results used directly: a slow API blocks the page for seconds, a 404 or 500 response is parsed as if it were data, and every page view calls the API again.
Solution: Pass explicit arguments, check is_wp_error() and the status code before using the body, return a WP_Error to the caller, cache successful responses in transients, and move slow or many calls to cron.
A GET request done right
<?php
function myplugin_get_repo_info( $repo ) {
$cache_key = 'myplugin_repo_' . md5( $repo );
$cached = get_transient( $cache_key );
if ( false !== $cached ) {
return $cached;
}
$response = wp_remote_get( 'https://api.github.com/repos/' . $repo, array(
'timeout' => 10, // seconds; the default is 5
'user-agent' => 'MyPlugin/1.0; ' . home_url(),
'headers' => array(
'Accept' => 'application/vnd.github+json',
'Authorization' => 'Bearer ' . get_option( 'myplugin_github_token' ),
),
) );
// Network errors: DNS, timeout, refused connection, SSL
if ( is_wp_error( $response ) ) {
return $response;
}
// HTTP errors: the request worked, but the answer is not the data
$status = wp_remote_retrieve_response_code( $response );
if ( 200 !== $status ) {
return new WP_Error( 'myplugin_api_error', sprintf( 'GitHub API returned HTTP %d', $status ), array( 'status' => $status ) );
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $data ) ) {
return new WP_Error( 'myplugin_json_error', 'Invalid JSON response' );
}
set_transient( $cache_key, $data, HOUR_IN_SECONDS );
return $data;
}
// The caller decides what to show
$info = myplugin_get_repo_info( 'owner/repo' );
if ( ! is_wp_error( $info ) ) {
echo esc_html( number_format_i18n( $info['stargazers_count'] ) );
}
The two checks are different: is_wp_error() means there was no HTTP response at all, the status code tells whether the response is what you asked for. wp_remote_get() does not treat 4xx and 5xx as errors.
SSL certificates are verified by default. Do not pass 'sslverify' => false outside a local test setup: it makes the request open to man-in-the-middle attacks, and the real fix for a certificate error is usually an outdated CA bundle or a misconfigured server.
A POST with a JSON body
<?php
function myplugin_send_webhook( $url, array $payload ) {
$response = wp_remote_post( $url, array(
'timeout' => 15,
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode( $payload ), // a string body is sent as is
) );
if ( is_wp_error( $response ) ) {
return $response;
}
$code = wp_remote_retrieve_response_code( $response );
return $code >= 200 && $code < 300 ? true : new WP_Error( 'myplugin_webhook_failed', 'HTTP ' . $code );
}
An array body is sent as a form (application/x-www-form-urlencoded); for JSON, encode it yourself and set the header. For fire-and-forget calls, 'blocking' => false returns at once, but then there is no response to check, so use it only where losing the call is acceptable.
Defaults, debugging, local development
<?php
// A default timeout for all requests
add_filter( 'http_request_timeout', function () {
return 15;
} );
// Log every outgoing request while debugging
add_action( 'http_api_debug', function ( $response, $context, $class, $args, $url ) {
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
$result = is_wp_error( $response ) ? $response->get_error_code() : wp_remote_retrieve_response_code( $response );
error_log( sprintf( '[HTTP] %s %s -> %s', $args['method'] ?? 'GET', $url, $result ) );
}
}, 10, 5 );
In wp-config.php of a local or staging copy, define( 'WP_HTTP_BLOCK_EXTERNAL', true ); blocks all outgoing requests, and define( 'WP_ACCESSIBLE_HOSTS', 'api.github.com,*.wordpress.org' ); allows the hosts you need.
Keep remote calls out of the page
Each wp_remote_get() blocks PHP until the response arrives, and the calls run one after another. A page that calls three APIs on a cache miss waits for all three. So:
- cache every successful response (the expiration depends on how fresh the data must be), see the Transients API;
- refresh data that is needed on every page in the background, with WP-Cron, so visitors never wait for the API;
- for several independent requests at once, the bundled Requests library can send them in parallel:
WpOrg\Requests\Requests::request_multiple().
NOTE: Never call a remote API inside the loop or on every wp_head without a cache: the page is then as slow as the slowest API and breaks when it is down. A failed request should leave the page working, with old data or without that block, never with a fatal error.