How To Make Api Requests In WordPress With Wp_Remote_Get And Wp_Remote_Post
WordPress has its own HTTP API for talking to external services. Use wp_remote_get() and wp_remote_post() instead of cURL, because they work on any hosting and respect the site settings.
GET request with a token
function lotgrafix_fetch_items() {
$response = wp_remote_get( 'https://api.example.com/items', array(
'timeout' => 15,
'headers' => array(
'Authorization' => 'Bearer ' . LOTGRAFIX_API_KEY,
'Accept' => 'application/json',
),
) );
if ( is_wp_error( $response ) ) {
error_log( $response->get_error_message() );
return array();
}
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
return array();
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
return is_array( $data ) ? $data : array();
}
POST request with JSON
$response = wp_remote_post( 'https://api.example.com/contacts', array(
'timeout' => 15,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . LOTGRAFIX_API_KEY,
),
'body' => wp_json_encode( array(
'name' => 'Lotgrafix',
'email' => 'hello@example.com',
) ),
) );
POST request with form data
Pass an array as the body and WordPress sends it as a normal form.
$response = wp_remote_post( 'https://example.com/endpoint', array(
'body' => array(
'name' => 'Lotgrafix',
'email' => 'hello@example.com',
),
) );
Helper functions
wp_remote_retrieve_response_code(): the HTTP status, like 200 or 404.wp_remote_retrieve_body(): the response body as a string.wp_remote_retrieve_headers(): all response headers.wp_remote_retrieve_header(): a single header.
Best practices
- Define API keys as constants in
wp-config.php, never inside theme files or JavaScript. - Always check for
WP_Errorand the status code before using the data. - Cache successful responses with transients so you do not call the API on every page load.
- When the URL comes from user input, use
wp_safe_remote_get()to block requests to internal addresses.


