WordPress wp_remote_get 函数远程获取的正确用法

原文链接:https://zhangzifan.com/wordpress-wp_remote_get.html

WordPress可以通过 wp_remote_get() 或者 wp_remote_post() 非常容易的获取到远程文件的内容或者信息,取代了php的 file_get_contents 函数或者 cURL,但是子凡在最近开发的一些插件功能却发现打开的方式不对,某些情况下会提示:Fatal error: Cannot use object of type WP_Error as array... 的类似错误,并且还会引起插件页面空白的情况。因为通过函数直接获取远程链接的信息,而并没有判断获取到的信息是否错误或者失败。

那么今天子凡就分享一个 wp_remote_get 函数正确的使用方法吧!

// wp_remote_get 函数正确使用方法
$response = wp_remote_get( 'https://zhan.leiue.com?plugin=Fanly Submit' );
if ( is_array( $response ) && !is_wp_error($response) && $response['response']['code'] == '200' ) {
	$header = $response['headers']; // array of http header lines
	$body = $response['body']; // use the content
}

以上代码示例判断了三个条件,首先肯定是判断获取的数据是否是数组,这也是 WordPress 官方对 wp_remote_get 函数的默认示例方法,而子凡认为还有必要使用 is_wp_error 函数来判断错误,同时还判断了返回的状态码是否为200,争取做到万无一失。