How to use HTTP Requests in WordPress: a practical guide with examples

When developing plugins or themes for WordPress, it’s common to need to connect to external services to fetch or send data. This is done using HTTP requests. In this article, we’ll explain what they are, how they work in WordPress, and give you practical examples so you can apply them to your projects.

 

What is an HTTP Request?

An HTTP request is a call your website makes to another server. For example, if your plugin needs to show the weather, it might send a request to a weather API like OpenWeatherMap and get the response in JSON format.

In WordPress, this is easily done using functions like wp_remote_get()and wp_remote_post().

 

Why use WordPress native functions?

Although you could use cURL or file_get_contents(), WordPress includes its own HTTP API that is:

  • Compatible with multiple server environments (cURL, fopen, fsockopen, etc.)
  • Secure (handles errors, redirects, SSL, etc.)
  • Easy to use

 

How to make a GET Request in WordPress

The GET method is used to retrieve data from an external server. For example, to get data from an API.

Example:

<?php
function getWeatherData() {
    $apiUrl     = 'https://api.openweathermap.org/data/2.5/weather?q=Lima,PE&appid=YOUR_API_KEY&units=metric';
    $response   = wp_remote_get( $apiUrl );

    if ( is_wp_error( $response ) ) {
        return 'Error retrieving weather data.';
    }

    $body       = wp_remote_retrieve_body( $response );
    $data       = json_decode( $body, true );

    if ( isset( $data['main']['temp'] ) ) {
        return 'Current temperature: ' . $data['main']['temp'] . '°C';
    }

    return 'Weather data not available.';
}

You can use this function in a shortcode or a hook to display the weather on your site.

 

How to make a POST Request in WordPress

The POST method is used to send data to a server, for example, to submit forms or create a resource in an API.

Example:

<?php
function sendContactData() {
    $apiUrl   = 'https://example.com/api/contact';
    $payload  = [
        'name'    => 'Juan Pérez',
        'email'   => 'juan@email.com',
        'message' => 'Hi, I’d like more information.'
    ];

    $response = wp_remote_post( $apiUrl, [
        'body'    => json_encode( $payload ),
        'headers' => [
            'Content-Type' => 'application/json',
        ],
    ]);

    if ( is_wp_error( $response ) ) {
        return 'Failed to send message.';
    }

    $body = wp_remote_retrieve_body( $response );
    return 'Server response: ' . $body;
}

 

How to handle errors properly

It’s very important to validate the response with is_wp_error()before processing it to avoid breaking your plugin if there are network issues or server errors.

You can also retrieve detailed error messages:

<?php
if ( is_wp_error( $response ) ) {
    $errorMessage = $response->get_error_message();
    return 'Error: ' . $errorMessage;
}

 

Adding Authentication (Bearer Token)

If the API requires authentication, you can add a custom header like this:

<?php
function getPrivateData() {
    $apiUrl   = 'https://private.api.com/data';
    $token    = 'YOUR_TOKEN_HERE';

    $response = wp_remote_get( $apiUrl, [
        'headers' => [
            'Authorization' => 'Bearer ' . $token,
        ],
    ]);

    if ( is_wp_error( $response ) ) {
        return 'Error accessing data.';
    }

    return wp_remote_retrieve_body( $response );
}

 

Where can you use these functions?

You can use wp_remote_get()and wp_remote_post()in:

  • Custom shortcodes
  • Plugin functions
  • Hooks like wp_ajax_ or rest_api_init
  • Cron jobs ( wp_schedule_event() )

HTTP requests allow your WordPress site to integrate with other services easily. Thanks to WordPress’s native functions, you don’t need to rely on external libraries or mess with cURL.

Whether you need to consume an API, send data, or authenticate users, wp_remote_get()and wp_remote_post() give you the tools to do it securely and simply.

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x