wp_remote_get( string $url, array $args = array() ): array|WP_Error

Performs an HTTP request using the GET method and returns its response.

Description

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.

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 wp-includes/http.php to get other parameters such as headers.

See WP_Http_Streams::request() method located in wp-includes/class-wp-http-streams.php 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

VersionDescription
2.7.0Introduced.

User Contributed Notes

  1. Skip to note 13 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.


    * @param string|array $args {
    * Optional. Array or string of HTTP request arguments.
    *
    * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
    * Some transports technically allow others, but should not be
    * assumed. Default 'GET'.
    * @type int $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/' . $wp_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.

  2. Skip to note 15 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 18 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 20 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 22 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 23 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 24 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
        }

You must log in before being able to contribute a note or feedback.