External API to WP

I have my own api of metadata(external to wp), and I would like to read some data through my api and show it on my WP Site.

I have been using the method wp_remote_get of the HTTP WP API. But I have two questions.

In what section should I place that requests, in functions.php? maybe making a plugin (seems a little hard)?, or with a plugin posting PHP on specific pages?

The other question: When I use the wp_remote_retrieve_body it returns a String with the body of the JSON, how I print it in a nice way and not like an ugly string?

Thanks in advance.

1 Answer
1

I’d recommend writing a simple plugin. Read through the Plugin Development Handbook, but it’s pretty easy. The only thing necessary for a plugin is the header with the Plugin Name.

In the plugin, create a function that gets and stores in a WordPress transient the result of an API request.

<?php
/**
 * Plugin Name: WordPress StackExchange Question 266688
 */

namespace StackExchange\WordPress;
//* If you are running a version of PHP less than 5.3, namespaces are not available
//* Instead, you can pseudo-namespace the function

//* Simple function to use the transients API to cache the result of the external API request
function get() {
  $transient = \get_transient( 'name_of_transient' );
  if( ! empty( $transient ) ) {
    return $transient;
  }
  $output = \wp_remote_get( 'https://api.example.com/v2/my-api/' );
  \set_transient( 'name_of_transient', json_decode( $output ), DAY_IN_SECONDS );
  return $out;      
}

To use the function:

//* This will be an object
$api = \Stackexchange\WordPress\get();
echo $api->example_property;

Leave a Comment