wp_remote_get()
云策文档标注
概述
wp_remote_get() 是 WordPress 中用于执行 HTTP GET 请求的核心函数,返回响应数组或 WP_Error 对象。开发者需注意安全性和参数配置,特别是在处理用户可控 URL 时。
关键要点
- 函数执行 HTTP GET 请求,返回响应数组或 WP_Error 对象,参数包括 URL 和可选的请求参数数组。
- 若 URL 用户可控,应使用 wp_safe_remote_get() 替代以增强安全性。
- 响应处理可使用 wp_remote_retrieve_body() 获取响应体,wp_remote_retrieve_response_code() 获取状态码。
- 请求参数 $args 支持多种选项,如超时、重定向、HTTP 版本、用户代理、头部、SSL 验证等,详细定义参考 WP_Http::request()。
- 函数内部调用 _wp_http_get_object()->get(),广泛用于 WordPress 核心功能如调试数据、站点健康检查、API 通信等。
代码示例
$response = wp_remote_get( 'http://www.example.com/index.html' );
if ( is_array( $response ) && ! is_wp_error( $response ) ) {
$headers = $response['headers'];
$body = $response['body'];
}注意事项
- 设置 headers 时,每个头部需作为数组元素,如 array('Content-Type' => 'application/json'),而非 cURL 风格的字符串。
- API 密钥限制域名时,需手动设置 referer 头部,因为 wp_remote_get() 不自动设置。
- 避免在 GET 请求中使用 body 参数,可能导致错误;应使用 wp_remote_post() 进行 POST 请求。
- 处理 JSON 响应时,建议检查响应码和 JSON 解码错误,以确保数据完整性。
原文内容
Performs an HTTP request using the GET method and returns its response.
Description
Important: If the URL is user-controlled, use wp_safe_remote_get() instead.
See also
- wp_remote_request(): For more information on the response array format.
- WP_Http::request(): For default arguments information.
Parameters
$urlstringrequired-
URL to retrieve.
$argsarrayoptional-
Request arguments.
See WP_Http::request() for information on accepted arguments.Default:
array()
Source
function wp_remote_get( $url, $args = array() ) {
$http = _wp_http_get_object();
return $http->get( $url, $args );
}
Changelog
| Version | Description |
|---|---|
| 2.7.0 | Introduced. |
Skip to note 14 content
Lance Cleveland
Valid arguments for the second parameter can be found in class-http.php in the header. There is not easy way to reference the list on the current version of this guide so I’m pasting the PHPDoc header here. Hopefully the docs site will expand the WP_Http page or find a way to reference the valid parameters through indirection while the robots build these pages.
<br />
* @param string|array $args {<br />
* Optional. Array or string of HTTP request arguments.<br />
*<br />
* @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.<br />
* Some transports technically allow others, but should not be<br />
* assumed. Default 'GET'.<br />
* @type int $timeout How long the connection should stay open in seconds. Default 5.<br />
* @type int $redirection Number of allowed redirects. Not supported by all transports<br />
* Default 5.<br />
* @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.<br />
* Default '1.0'.<br />
* @type string $user-agent User-agent value sent.<br />
* Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).<br />
* @type bool $reject_unsafe_urls Whether to pass URLs through wp_http_validate_url().<br />
* Default false.<br />
* @type bool $blocking Whether the calling code requires the result of the request.<br />
* If set to false, the request will be sent to the remote server,<br />
* and processing returned to the calling code immediately, the caller<br />
* will know if the request succeeded or failed, but will not receive<br />
* any response from the remote server. Default true.<br />
* @type string|array $headers Array or string of headers to send with the request.<br />
* Default empty array.<br />
* @type array $cookies List of cookies to send with the request. Default empty array.<br />
* @type string|array $body Body to send with the request. Default null.<br />
* @type bool $compress Whether to compress the $body when sending the request.<br />
* Default false.<br />
* @type bool $decompress Whether to decompress a compressed response. If set to false and<br />
* compressed content is returned in the response anyway, it will<br />
* need to be separately decompressed. Default true.<br />
* @type bool $sslverify Whether to verify SSL for the request. Default true.<br />
* @type string sslcertificates Absolute path to an SSL certificate .crt file.<br />
* Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.<br />
* @type bool $stream Whether to stream to a file. If set to true and no filename was<br />
* given, it will be droped it in the WP temp dir and its name will<br />
* be set using the basename of the URL. Default false.<br />
* @type string $filename Filename of the file to write to when streaming. $stream must be<br />
* set to true. Default null.<br />
* @type int $limit_response_size Size in bytes to limit the response to. Default null.<br />
Skip to note 15 content
Codex
Get a remote URL
/** @var array|WP_Error $response */ $response = wp_remote_get( 'http://www.example.com/index.html' ); if ( is_array( $response ) && ! is_wp_error( $response ) ) { $headers = $response['headers']; // array of http header lines $body = $response['body']; // use the content }Skip to note 16 content
Kalimah Apps
The top comment by Store Locator Plus adds good information but it is hard to read.
To find the arguments you can see WP_Http::request documentation or see below for a formatted PHPDoc version:
/** * @param string|array $args { * Optional. Array or string of HTTP request arguments. * * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', 'PUT', 'DELETE', * 'TRACE', 'OPTIONS', or 'PATCH'. * Some transports technically allow others, but should not be * assumed. Default 'GET'. * @type float $timeout How long the connection should stay open in seconds. Default 5. * @type int $redirection Number of allowed redirects. Not supported by all transports * Default 5. * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'. * Default '1.0'. * @type string $user-agent User-agent value sent. * Default 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ). * @type bool $reject_unsafe_urls Whether to pass URLs through wp_http_validate_url(). * Default false. * @type bool $blocking Whether the calling code requires the result of the request. * If set to false, the request will be sent to the remote server, * and processing returned to the calling code immediately, the caller * will know if the request succeeded or failed, but will not receive * any response from the remote server. Default true. * @type string|array $headers Array or string of headers to send with the request. * Default empty array. * @type array $cookies List of cookies to send with the request. Default empty array. * @type string|array $body Body to send with the request. Default null. * @type bool $compress Whether to compress the $body when sending the request. * Default false. * @type bool $decompress Whether to decompress a compressed response. If set to false and * compressed content is returned in the response anyway, it will * need to be separately decompressed. Default true. * @type bool $sslverify Whether to verify SSL for the request. Default true. * @type string $sslcertificates Absolute path to an SSL certificate .crt file. * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'. * @type bool $stream Whether to stream to a file. If set to true and no filename was * given, it will be droped it in the WP temp dir and its name will * be set using the basename of the URL. Default false. * @type string $filename Filename of the file to write to when streaming. $stream must be * set to true. Default null. * @type int $limit_response_size Size in bytes to limit the response to. Default null. * * } */Skip to note 17 content
Codex
Get a remote URL with special arguments
/** @var array|WP_Error $response */ $response = wp_remote_get( 'http://www.example.com/index.php?action=foo', array( 'timeout' => 120, 'httpversion' => '1.1', ) );Skip to note 18 content
dleeward
When adding headers, each part of the header has to be a separate element like this:
$args = array( 'headers' => array( 'Content-Type' => 'application/json', 'X-Api-Key' => 'apikey12345' )not like cURL where you can use ‘Content-Type: application/json’
Skip to note 19 content
ancientro
If you load data from an API and have set a domain restriction on the API key (such as only allow on “www.example.com/*”), you need to set the “referer” in “headers” in $args, as wp_remote_get() does not set the referer automatically:
$response = wp_remote_get( esc_url_raw( $api_url ), array( 'headers' => array( 'referer' => home_url() ) ) );Or, as a string, to work on your localhost as well:
'referer' => 'www.example.com'Skip to note 20 content
Manny (emanweb)
It would be cool to have a link to this somewhere on this page: https://developer.wordpress.org/reference/functions/wp_safe_remote_get/
Skip to note 21 content
Lisa Linn Allen
replace
wp_get_http( $url, $filename )to get a remote file and write to the file system:$args_for_get = array( 'stream' => true, 'filename' => $filename, ); $response = wp_remote_get( $url, $args_for_get );Thank you @charlestonsw for pasting in the comments with the meaning of all the args, which lead me to this simple replacement.
Skip to note 22 content
Khoi Pro
It’s better to execute JSON response like that to keep it managed.
$request = wp_remote_get($url, $options); return load_request($request); function load_request($response) { try { $json = json_decode( $response['body'] ); } catch ( Exception $ex ) { $json = null; } return $json; }Skip to note 23 content
Namith Jawahar
An example for reading a JSON response from an API end point with error checking.
Here we are checking for the response code of 200 utilizing the wp_remote_retrieve_response_code() function and also verifying there are no JSON errors during the json_decode() function call utilising the json_last_error() function.
try { $response = wp_remote_get( 'https://yourapi.end/point/', array( 'headers' => array( 'Accept' => 'application/json', ) ) ); if ( ( !is_wp_error($response)) && (200 === wp_remote_retrieve_response_code( $response ) ) ) { $responseBody = json_decode($response['body']); if( json_last_error() === JSON_ERROR_NONE ) { //Do your thing. } } } catch( Exception $ex ) { //Handle Exception. }Skip to note 24 content
Matej Podstrelenec
You may come across following error:
http_build_query() expects parameter 1 to be array, string givenThat happens when you try using wp_remote_get() with body parameter. This is not a recommended standard and WordPress will not let you do it.
Use wp_remote_post() instead.
Example:
$response = wp_remote_post( $api_url, array( 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key ), 'body' => json_encode( $body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) ) );Skip to note 25 content
zauddelig
You can use it to fetch external Authenticated APIs
// If the API is using a Bearer Token $auth_scheme = 'Bearer'; $api_key = 'token'; // If the API is using Basic Auth $auth_scheme = 'Basic'; $api_key = base64_encode( 'username' . ':' . 'password' ); // set the API URL and make the request. $api_url = 'https://...'; $response = wp_remote_get( $api_url, array( 'headers' => array( 'Accepts' => 'application/json', 'Authorization' => $auth_scheme . ' ' . $api_key ), ) ); if ( is_wp_error( $response ) ) { ... // Handle the error } else { $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); ... // do something with the data }Skip to note 26 content
Shah Alom
$apiUrl = 'https://example.com/wp-json/wp/v2/posts?page=0&per;_page=0'; $response = wp_remote_get($apiUrl); $responseBody = wp_remote_retrieve_body( $response ); $result = json_decode( $responseBody ); if ( is_array( $result ) && ! is_wp_error( $result ) ) { // Work with the $result data } else { // Work with the error }$result = json_decode($responseBody);if success as it is will return an object and not a array, my friend, so the if will fail even if there are no errors. Consider changing line 4 to:$result = json_decode($responseBody, true);json_decode()is native to PHP, and so will never return an instance ofWP_Errorobject; that check is unnecessary, or, should be adjusted to check$response.