Function Name: wp_remote_request
The wp_remote_request function is a WordPress core function that allows developers to send an HTTP request to a specified URL and retrieve the response. This function can be used for a variety of purposes, such as fetching data from external sources, interacting with APIs, and more.
The function takes two arguments: $url, which specifies the URL to which the HTTP request should be sent, and $args, which is an optional array of parameters that can be used to customize the request.
The $args array can contain a number of different parameters, such as headers, body content, request method, and more. By default, the function uses the GET method to send the request, but this can be changed by setting the ‘method’ parameter to POST or another supported method.
Once the request is sent, the function returns an array containing the HTTP response code, headers, and body content. This allows developers to parse the response and use it as needed in their code.
Here is an example usage code for the wp_remote_request function:
$response = wp_remote_request( 'https://example.com/api/data', array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer 1234567890',
'Content-Type' => 'application/json',
),
'body' => json_encode( array(
'param1' => 'value1',
'param2' => 'value2',
) ),
) );
if ( is_wp_error( $response ) ) {
// Handle error
} else {
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );
// Parse response as needed
}
In this example, we send a POST request to the ‘https://example.com/api/data‘ URL, passing along an authorization token and JSON-encoded request body content. We then check for any errors in the response and retrieve the response code and body content for further processing.