Skip to content

Instantly share code, notes, and snippets.

@coulterpeterson
Last active June 29, 2021 23:47
Show Gist options
  • Save coulterpeterson/090bfab89cce9060715152ac1f24bdaa to your computer and use it in GitHub Desktop.
Save coulterpeterson/090bfab89cce9060715152ac1f24bdaa to your computer and use it in GitHub Desktop.
My function for calling REST endpoints from WordPress
<?php
// ... functions.php stuff ....
// START HELPER API CALL FUNCTION
function makeApiCall( $url, $payload, $method = 'POST', $dataType = 'formData', $authHeader = null ) {
$headers = array();
if($dataType === 'json') {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
$payloadToSend = $payload;
} else {
$headers['Content-Type'] = 'application/json; charset=utf-8';
$payloadToSend = json_encode($payload);
}
if($authHeader)
$headers['Authorization'] = $authHeader;
$response = wp_remote_request( $url, array(
'method' => $method,
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.1',
'blocking' => true,
'headers' => $headers,
'body' => $payloadToSend,
'cookies' => array(),
) );
if ( is_wp_error( $response )) {
$error_message = $response->get_error_message();
return array( false, $error_message );
} else if ( wp_remote_retrieve_response_code($response) !== 200 ) {
return array( false, $response );
} else {
return array( true, wp_remote_retrieve_body($response) );
}
}
// END HELPER API CALL FUNCTION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment