函数文档

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

Parameters

$urlstringrequired
URL to retrieve.
$argsarrayoptional
Request arguments.
See WP_Http::request() for information on accepted arguments.

Default:array()

Return

array|WP_Error The response or WP_Error on failure.
See WP_Http::request() for information on return value.

More Information

Use wp_remote_retrieve_body( $response ) to get the response body.

Use wp_remote_retrieve_response_code( $response ) to get the HTTP status code for the response.

Use related functions in <a class="external text" href="https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/http.php#L207" rel="nofollow">wp-includes/http.php</a> to get other parameters such as headers.

See WP_Http_Streams::request() method located in <a class="external text" href="https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-http-streams.php#L287" rel="nofollow">wp-includes/class-wp-http-streams.php</a> for the format of the array returned by wp_remote_get() .

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.

User Contributed Notes

  1. Skip to note 14 content

    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 />

  2. Skip to note 16 content

    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.
    *
    * }
    */

  3. Skip to note 19 content

    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'

  4. Skip to note 21 content

    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.

  5. Skip to note 23 content

    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.
    }

  6. Skip to note 24 content

    You may come across following error:

    http_build_query() expects parameter 1 to be array, string given

    That 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 )
    ) );

  7. Skip to note 25 content

    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
    }

  8. Skip to note 26 content

        $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
        }