Last active
November 6, 2019 06:57
-
-
Save raazon/76c32238836bd6c54238027b7be75851 to your computer and use it in GitHub Desktop.
Wordpress http api
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 | |
/* | |
* Ref 1: https://developer.wordpress.org/plugins/http-api/ | |
* Ref 2: https://developer.wordpress.org/reference/functions/wp_remote_request/ | |
* Dummy API Credit: https://jsonplaceholder.typicode.com/ | |
*/ | |
// Get a resource | |
$args = array( | |
'method' => 'GET', | |
); | |
$response = wp_remote_request( 'https://jsonplaceholder.typicode.com/users/1', $args); | |
$http_code = wp_remote_retrieve_response_code( $response ); | |
$body = wp_remote_retrieve_body( $response ); | |
$body_decode = json_decode($body); | |
var_dump($http_code); | |
var_dump($body); | |
// Create a resource | |
$args = array( | |
'method' => 'POST', | |
'headers' => array( | |
'Content-type' => 'application/json; charset=UTF-8', | |
), | |
'body' => json_encode( | |
array( | |
'title' => 'foo', | |
'body' => 'bar', | |
'userId' => 1, | |
) | |
), | |
); | |
$response = wp_remote_request( 'https://jsonplaceholder.typicode.com/posts', $args); | |
$http_code = wp_remote_retrieve_response_code( $response ); | |
$body = wp_remote_retrieve_body( $response ); | |
$body_decode = json_decode($body); | |
var_dump($http_code); | |
var_dump($body); | |
// Update a resource | |
$args = array( | |
'method' => 'PUT', | |
'headers' => array( | |
'Content-type' => 'application/json; charset=UTF-8', | |
), | |
'body' => json_encode( | |
array( | |
'id' => 1, | |
'title' => 'foo', | |
'body' => 'bar', | |
'userId' => 1, | |
) | |
), | |
); | |
$response = wp_remote_request( 'https://jsonplaceholder.typicode.com/posts/1', $args); | |
$http_code = wp_remote_retrieve_response_code( $response ); | |
$body = wp_remote_retrieve_body( $response ); | |
$body_decode = json_decode($body); | |
var_dump($http_code); | |
var_dump($body); | |
// Delete a resource | |
$args = array( | |
'method' => 'DELETE', | |
); | |
$response = wp_remote_request( 'https://jsonplaceholder.typicode.com/posts/1', $args); | |
$http_code = wp_remote_retrieve_response_code( $response ); | |
$body = wp_remote_retrieve_body( $response ); | |
$body_decode = json_decode($body); | |
var_dump($http_code); | |
var_dump($body); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment