How to make GET request in wordpress ?
In WordPress, you can make a GET request using the wp_remote_get()
function. This function is a wrapper for the cURL
library and allows you to send GET requests to a specified URL.
Here is an example of how you can use the wp_remote_get()
function to make a GET request:
$response = wp_remote_get( ‘https://example.com' );
if ( is_wp_error( $response ) ) {
// handle error
} else {
$data = json_decode( wp_remote_retrieve_body( $response ) );
// do something with data
}
In this example, the wp_remote_get()
function is used to send a GET request to the URL "https://example.com". The response is then stored in the $response
variable. If the response is an error, the is_wp_error()
function is used to check for it and handle it. If the response is successful, the json_decode()
function is used to parse the JSON data that is returned in the response body.
You can also pass an array of arguments as a second parameter to the wp_remote_get()
function to customize the request, like headers, body, timeout, redirects, http version etc.
$response = wp_remote_get( 'https://example.com', array(
'headers' => array(
'Accept-Language' => 'en-US'
),
'timeout' => 30,
'redirection' => 5,
'httpversion' => '1.1',
'sslverify' => false
));
Please be aware that, wordpress also have a nonce security mechanism to prevent CSRF attacks, you may need to verify the nonce before making a GET request.