WordPress remote functions are great to handle requests with other services. If you have various APIs which you want to access using WordPress, you can use those functions for everything. They can become a little cumbersome with all those settings, but with object oriented programming we can make our requests easier and even more readable.

WordPress Remote Functions

There are various WordPress remote functions. All of them are using the WordPress HTTP object so they actually operate with the same set of data but each request method does something a little different. Because of that, WordPress has a set of easy remote functions that will handle most for us:

All those functions are used to get a response. WordPress made some other functions which will make retrieving the body or headers of the response even easier:

Request Arguments

Arguments that can be sent in those requests are and are set by default:

  • method – request method such as GET, POST or PUT,
  • timeout – the maximum time for connection to stay open in seconds. Default is 5 seconds,
  • redirection – allowed redirections. Default if 5,
  • httpversion – version of http protocol which can be 1.0 or 1.1. Default is 1.0,
  • user-agent – default is ‘WordPress/WP_VERSION; URL’,
  • reject_unsafe_urls – if true, it will validate the url. Default is false,
  • blocking – if false, it will not return any response from the remote server. Default is true,
  • headers – this is a string or array of headers that will be sent. Default is an empty array,
  • cookies – list of cookies which will be sent in the request. Default is an empty array,
  • body – data that will be sent with the request. Default is null,
  • compress – compress the data (body) or not. Default is false,
  • decompress – if true it will decompress the response. If false, another operation will need to decompress the response. Default is true,
  • sslverify – if true, it will verify the SSL for the request. Default is true,
  • sslcertificates – absolute path to a certificate,
  • stream – if true, it will stream to a file. When there is no filename, it will be created from the basename of the URL,
  • filename – filename to which the stream will write,
  • limit_response_size – size in bytes to which the response will be limited. Default is null.

Request Response

The request will respond with an array or as a WP_Error object. The array will contain:

  • headers,
  • body,
  • response,
  • cookies and
  • filename.

WordPress Remote Class

We will start building our class with a few attributes that we will use to store response data and request data. This is the first part of our remote class:

If you wonder why our attributes are set to protected and not public or private, then you should know that a public attribute is accessible even outside our class/object so it could be change within the code. The private attribute is accessible only in that class and any class that will extend our main class will not have those private attributes. Protected attributes are similar to private attributes since they are not accessible outside the class/object but they are also transferred to other classes.

In our constructor method, we are assuring that the method will be in uppercase. After that we are setting our request url and the arguments for the request. Finally we are also setting our method as an argument that will define the type of our request.

So, if you look closely, our constructor method is used only to assign our passed values to our attributes. It will not make a request or get a response. This will be done by a separate method:

Here we are using the function wp_remote_request to get the response data. After that we are using the response data to retrieve the body of the request, headers, response code and message.

Since all of our attributes are protected, we need to have some methods that will be used to retrieve that information:

All of this method are simple methods used to retrieve some data from the request. We could also extend it and have a helper method to show if we did succeed or not:

Extending a Class for JSON requests

In this simple example, we will extend our class with a new one to have a class that will handle JSON requests or responses. The only difference here is that we will automatically set the content type in the headers we send:

Here we have extended our array of arguments with another headers content. Once we did that, we are simply running my parents’  method with the same name.

Examples

For this examples I will use the leanpub API since it is a simple one and we can retrieve information even if you are not a registered member. Some of data will not be available and you will not be able to create successful post requests, but that is just fine for this example.

Success

This is a simple get request that is made by just providing the url for the request.

Failure

In this example, the response is false because we are trying to create coupons for this ebook and we are not providing the request with the API key that is needed for us to be able to make coupons for this ebook (if the ebook is ours).

Conclusion

With some simple modifications we can easily create various classes for various remote requests. By using object oriented programming for remote functions in WordPress we can make the development much faster and easier.

Have you ever used the remote functions in WordPress? Share your experience below in the comments.

Become a Sponsor

Posted by Igor Benic

Web Developer who mainly uses WordPress for projects. Working on various project through Codeable & Toptal. Author of several ebooks at https://leanpub.com/u/igorbenic.

6 Comments

    1. I am glad you find it useful:)

      Reply

  1. Very good info , thanks

    Reply

  2. Really very good info , thanks .

    Reply

  3. Hello Igor,
    very useful article indeed!
    I don’t know if you can help me but i thought i’ll give it a shot.
    I’m currently trying to get data from an external source (not a Wp site) to a Wp site using the wp_remote_get method.
    Everything runs smoothly if i make the request to a site that has a json file.
    But the external site that i want to retrieve data from doesn’t have an actual json file instead they provide this address to use if you want to make the request ( https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139).
    The problem now is that i get the response back using the below code

    $url = ‘ https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139‘;

    $request = wp_remote_get( $url );

    if(is_wp_error($request)) {
    return false;
    } else {
    $body = $request[‘body’];
    }

    echo $body;
    $api_response = json_decode( wp_remote_retrieve_body( $response ), true );

    but it displays in a raw format like this

    {“coord”:{“lon”:139,”lat”:35},”weather”:[{“id”:803,”main”:”Clouds”,”description”:”broken clouds”}],”base”:”stations”,”main”:{“temp”:28.23,”pressure”:1011,”humidity”:74,”temp_min”:26,”temp_max”:31},”visibility”:10000,”wind”:{“speed”:3.6,”deg”:230},”clouds”:{“all”:75},”dt”:1499396400,”sys”:{“type”:1,”id”:7616,”message”:0.0043,”country”:”JP”,”sunrise”:1499369792,”sunset”:1499421666},”id”:1851632,”name”:”Shuzenji”,”cod”:200}

    Do you know how can i decode this and make it display as html elements?

    Any help would be highly appreciated.
    Thank you very much in advance.

    Reply

    1. Hi, you are echoing the body before you decode it. The $api_response in the code above should contain an array with data. Try print_r on that variable.

      Reply

Leave a reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.