Last active
June 29, 2021 23:47
-
-
Save coulterpeterson/090bfab89cce9060715152ac1f24bdaa to your computer and use it in GitHub Desktop.
My function for calling REST endpoints from WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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