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.

  • 3
    First: Make it a plugin. It's not really that difficult -- see Writing a Plugin or this tutorial. Second: Look into json_decode(), which will convert your "ugly string" into an object which you can then manipulate.
    – Pat J
    Commented May 12, 2017 at 12:58
  • To echo Pat, definitely make it a plugin. Putting it in functions.php is grouping it all to the theme's files. You change themes, you have to add it all back in. You absolutely want that level of functionality independent of any theme's context, and developed to be so. Nathan's answer below, and Pat's comment above, are two great starting points.
    – hwl
    Commented May 12, 2017 at 19:19

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.

 * 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;
  • In what part should I place the code to use the function?
    – PenDragon
    Commented May 15, 2017 at 8:59
  • The first codeblock should be in its own file. It can either reside directly in the wp-content/plugins folder or in a suitably named subfolder. You can then call/use the function in whatever PHP file that you want (that loads after the plugin is loaded). Commented May 15, 2017 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.