wp_remote_get

Home » Functions » wp_remote_get

Function Name: wp_remote_get

Explanation: The wp_remote_get function is a powerful WordPress function that allows you to send HTTP GET requests to external URLs and retrieve the response. It is commonly used to fetch data from remote APIs, retrieve content from external websites, or interact with other web services.

This function takes a URL as its parameter and sends an HTTP GET request to that URL. It then returns the response received from the remote server, which can be a string or an array, depending on the server’s response.

Usage Example: Let’s say you want to retrieve the latest weather data from a weather API and display it on your WordPress site. You can use the wp_remote_get function to fetch the data from the API endpoint. Here’s an example code snippet that demonstrates the usage of wp_remote_get:

$url = 'https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=New+York';
$response = wp_remote_get($url);

if (is_wp_error($response)) {
    // Handle error
    echo "Error: " . $response->get_error_message();
} else {
    // Retrieve and display the weather data
    $data = wp_remote_retrieve_body($response);
    $weather = json_decode($data);

    echo "Current temperature in New York: " . $weather->current->temp_c . "°C";
}

In this example, we first define the URL of the weather API endpoint, including the necessary query parameters. We then call the wp_remote_get function with the URL as the parameter, which sends the GET request to the API and returns the response. We then check if any errors occurred during the request using is_wp_error function.

If there are no errors, we retrieve the response body using the wp_remote_retrieve_body function and decode it from JSON format using json_decode. Finally, we extract the current temperature from the decoded data and display it on our WordPress site.

Remember to replace "YOUR_API_KEY" with your actual API key to make the code work correctly.

This is just one example of how the wp_remote_get function can be used in WordPress. Its versatility and simplicity make it a valuable tool for interacting with external services and fetching data from remote sources.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.