官术网_书友最值得收藏!

HTTP API in WordPress

As the name suggests, in WordPress, the HTTP API can be used to simplify HTTP requests. It can let you make HTTP requests via PHP, either to the same site or to a different site. But more importantly, HTTP API in WordPress lets you transform URL strings into JSON objects.

Consider the following URL string: http://example.com/wp-json/wp/v2/posts.

It is like any other URL on the Internet. Now, with HTTP API, we can convert it into a JSON object, making use of the wp_remote_get () function from the WordPress core:

$json = wp_remote_get ( 'http://example.com/wp-json/wp/v2/posts' ); 

Now, $json will yield an array, and that is precisely the response that we need.

To understand it better, let us now put together a very small function that accepts a URL string and then gives an array of post objects:

$response = wp_remote_get( $url ); 
function get_json( $url ) { 
//GET remote site 
$response = wp_remote_get( $url ); 
//Checking for errors 
if ( is_wp_error( $response ) ) { 
return sprintf( 'Your URL %1s could not be retrieved', $url ); 
//GET only body 
$data = wp_remote_retrieve_body( $response ); 
  } 
//return if no error 
if ( ! is_wp_error( $response ) ) { 
//Now, decode and return 
return json_decode( $response ); 
  } 
} 

What does the preceding code do? It makes a GET request and loads the URL string. To be sure that we are doing everything alright, we check whether our parameter is part of the WP_Error class or not because if it is, we have encountered an error. And if it is not, we can proceed with the JSON object.

Now, to test the preceding function, you can just pass any URL string for $url. Why not give it a shot and pass the URL to your test installation of WordPress, whatever it might be?

Ideally, the following is what your output should look like; it is pretty raw, but for a test code, this should show you that it works:

主站蜘蛛池模板: 金门县| 微山县| 龙山县| 江山市| 吴桥县| 射阳县| 商城县| 荣昌县| 腾冲县| 徐州市| 乐都县| 乌拉特前旗| 富阳市| 全州县| 洞头县| 马山县| 乃东县| 五家渠市| 安龙县| 资源县| 紫阳县| 兴城市| 苏尼特左旗| 剑河县| 德庆县| 靖州| 潼关县| 赤峰市| 库车县| 瑞安市| 塔城市| 阳春市| 同江市| 丁青县| 辽阳县| 苏尼特左旗| 拜泉县| 濉溪县| 纳雍县| 合江县| 汝南县|