day 41

Making HTTP requests from wordpress ?

We can make HTTP requests like GET,POST and HEAD using the helper functions in core.

The methods we can use are in the http.php file.

  • wp_remote_get()
  • wp_remote_post()
  • wp_remote_head()

We can use this methods to make the respective requests

// The GET

 $url = 'http://getit.local/wp-json/';
 $response = wp_remote_get($url);

 echo '<pre>'; 
 print_r($response);
 echo '</pre>';

This will make GET request and return the response

There are also some helper functions to get only the body or only some specific header

  • wp_remote_retrieve_body()
  • wp_remote_retrieve_response_code()
  • wp_remote_retrieve_header()
wp_remote_retrieve_body()
  • retrieves the body of the response
 $url = 'http://getit.local/wp-json/';
 $response = wp_remote_get($url);
 $body = wp_remote_retrieve_body($response);
wp_remote_retrieve_response_code()
  • Retrieves the response code
 $url = 'http://getit.local/wp-js0n/';
 $response = wp_remote_get($url);
 $response_code = wp_remote_retrieve_response_code($response);
 if(200 !== $response_code){
	echo __('Might be some issue');
 }

We can get all the headers or a specific header, for that we can use wp_remote_retrieve_header() or wp_remote_retrieve_headers() to get the headers as array


Transient API

In wordpress transient api can be used to cache the data in a standard way and for a specific time frame.

These API methods are in the option.php file, as the transient is just using the options API with timed expiration.

We can get and set the transient, we have to use a unique identifier for that.

  • get_transient()
  • set_transient()
  • delete_transient()

Also, if we are in a multisite setup and want the transient to be accessible network wide we can use the site_ methods

  • get_site_transient()
  • set_site_transient()
  • delete_site_transient()
$url = 'https://api.github.com/users/pratik-londhe4';
$response = wp_remote_get($url);
$body = wp_remote_retrieve_body($response);
set_transient('github-user', $body, 60);

$user = get_transient('github-user');
echo '<pre>';
print_r($user);
echo '</pre>';

Code to test the transient api.

We can set the expiration of the transient as the thir argument, we can use seconds or there are constants that we can use to define the time.

  • MINUTE_IN_SECONDS
  • HOUR_IN_SECONDS
  • DAY_IN_SECONDS
  • WEEK_IN_SECONDS
  • MONTH_IN_SECONDS
  • YEAR_IN_SECONDS

Comments

Leave a Reply

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