wp_remote_request()
Creates any type of HTTP request and returns the response of the request as an array.
There are wrappers for this function:
GET
- wp_remote_get()POST
- wp_remote_post()HEAD
- wp_remote_head()
If you send a request to a dynamic URL that can get any data, then it's better to use a safe function for this: wp_safe_remote_request()
No Hooks.
Return
Array|WP_Error
. The response array or a WP_Error on failure.
Returned array structure:
$res = array( 'headers' => array, 'response' => array( 'code' => int, 'message' => string ), 'body' => string, 'cookies' => array, 'filename' => string );
The response headers places in headers
index, which contains an array of response header data. So to get the User-Agent, use: $user_agent = $res['headers']['user-agent'];
The content of the response places in body
index.
Usage
wp_remote_request( $url, $args );
- $url(string) (required)
- Site URL to retrieve.
- $args(array)
Request arguments.
-
body – an array of request parameters where key is the name of the parameter and the value is its value:
array( 'foo'=>'val', 'bar'=>'val' )
Note: used for
PUT
,POST
methods only.Default: null
-
method — request HTTP method: POST, GET, HEAD, PUT, DELETE.
Default: 'GET' -
headers(string/array)
Headers to send with a request.
Default: array() -
cookies(array)
Cookies to send with a request. See: WP_Http::normalize_cookies(), WP_Http::buildCookieHeader().
Default: array() -
timeout — time in seconds, before the connection is dropped and an error is returned. The time can be changed in the plugin through the filter http_request_timeout.
Default: 5 -
redirection — the amount of times to follow a redirect before giving up. There is a filter for the value: http_request_redirection_count.
Default: 5 -
user-agent — it allows you to set the user-agent. There is a filter for changing this value: http_headers_useragent.
Default: 'WordPress/' . $wp_version . '; ' . get_bloginfo('url') -
blocking — allows you to trigger a non-blocking request. The default is true; setting it to false will generally allow PHP to continue execution while the transport is working. The key is that when you set blocking to false, then it will just send the request and won't bother you with the details. This is useful for sending a POST request, where you aren't concerned with whether it succeeded or not, or if you don't want to slow down the processing time of the page. (Note that not all the transports support non-blocking requests, and so you may still be blocked anyway. The alternative of setting an ultra-low timeout is not recommended, since low timeouts may cause the request to not be sent at all with some transports.)
May not work on some types of servers.
Default: true -
compress — allows you to send the request body as compressed.
Default: true -
decompress — Responsible for accept-encoding request header. If you do leave this as true, then the headers will be set to tell the server that compressed data is accepted and it will be decompressed in the response. If you sent it to false, then the header will be sent that tells servers that compressed content is not accepted. If the content is still compressed, because of incorrect implementation or you sent the headers for it, then you will need to decompress the content.
Default: true -
sslverify — true - will check to see if the SSL certificate is valid (not self-signed, actually for the site in the request) and will deny the response if it isn't. If you are requesting HTTPS and know that the site is self-signed or is invalid and are reasonably sure that it can be trusted, then set to false.
Default: true -
sslcertificates — Absolute path to ".crt" SSL certificate.
Default: ABSPATH . WPINC .'/certificates/ca-bundle.crt' -
stream(bool)
Whether to write data to a file. If set to true and the filename parameter is not specified, the data will be written to a file named basename(URL) in the WP temporary directory.
Default: false -
filename(string)
The filename (path) where to save the stream when the parameter stream = true.
Default: null -
limit_response_size(integer)
The size in bytes that you want to limit the response to.
Default: null - reject_unsafe_urls(bool)
Whether to clear the passed URL through the function wp_http_validate_url()
Default: false
See the class code for a complete list of parameters: WP_Http{}
Default: empty array
-
Examples
#1 Get GitHub user data
GitHub provides an API. So let's use it and get the erusev
user data.
$response = wp_remote_request( 'https://api.github.com/users/erusev' ); print_r( $response ); /* will output: Array ( [headers] => Array ( [server] => GitHub.com [date] => Thu, 10 Dec 2015 10:33:03 GMT [content-type] => application/json; charset=utf-8 [connection] => close [status] => 200 OK [x-ratelimit-limit] => 60 [x-ratelimit-remaining] => 57 [x-ratelimit-reset] => 1449746444 [cache-control] => public, max-age=60, s-maxage=60 [last-modified] => Mon, 23 Nov 2015 13:19:37 GMT [etag] => W/"c8dad0c81351ce6451a9b7de7f7f0d8b" [vary] => Array ( [0] => Accept [1] => Accept-Encoding ) [x-github-media-type] => github.v3 [x-xss-protection] => 1; mode=block [x-frame-options] => deny [content-security-policy] => default-src 'none' [access-control-allow-credentials] => true [access-control-expose-headers] => ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval [access-control-allow-origin] => * [strict-transport-security] => max-age=31536000; includeSubdomains; preload [x-content-type-options] => nosniff [x-served-by] => a241e1a8264a6ace03db946c85b92db3 [content-encoding] => gzip [x-github-request-id] => 05659C50:1D261:3E06B1C:566954DF ) [body] => {"login": "erusev", "id":184170, etc.} [response] => Array ( [code] => 200 [message] => OK ) [cookies] => Array ( ) [filename] => ) */
#2 Setting cookies for a query [auto-translate]
An example of how to set your cookies along with a WordPress query:
$request_args = [ 'method' => 'POST', 'headers' => [ 'Authorization' => 'Basic ' . base64_encode( 'log:pass' ), ], 'cookies' => [ 'my_cook' => 'my_cook value', ], ]; $resp = wp_remote_request( $request_args );
Or you can specify an object where you can specify additional cookie parameters:
$request_args = [ 'method' => 'POST', 'headers' => [ 'Authorization' => 'Basic ' . base64_encode( 'log:pass' ), ], 'cookies' => [ new \WP_Http_Cookie( [ 'name' => 'my_cook', 'value' => 'my_cook value', 'expires' => time() + ( DAY_IN_SECONDS * 7 ), 'path' => '/', ] ), ], ]; $resp = wp_remote_request( $request_args );
See WP_Http_Cookie::__construct() for all possible parameters.
Notes
- See: WP_Http::request() For information on default arguments.
Changelog
Since 2.7.0 | Introduced. |
wp_remote_request() wp remote request code WP 6.6.2
function wp_remote_request( $url, $args = array() ) { $http = _wp_http_get_object(); return $http->request( $url, $args ); }