essxiv essxiv - 3 months ago 24
reST (reStructuredText) Question

Making Simple Rest API call in Wordpress Pages and Widgets

I'm trying to make a simple api call to a site that needs to render the data in a Wordpress Page/Widget.

I created a new page and put this code in the editor box on my dashboard:

<?php
$response = wp_remote_get( 'https://jsonplaceholder.typicode.com/posts/2' );
if( is_array($response) ) {
$header = $response['headers'];
$body = $response['body'];
}
print($response);
print($header);
print($body);
?>


Nothing is rendering on my Wordpress UI.

Yes, i'm on my local environment (using MAMP).

Answer

Solution:

Create a folder in your plugin directory and create a .php file that will be containing your api calls.

Your structure will look something like this:

class Api extends WP_Widget {

function __construct() {
    $options = array(
        'description' => '',
        'name' => ''
    );
    parent::__construct('Api', 'Widget', $options);
}

public function form($instance) {

    extract($instance);
    // Put your HTML widget form here
}

public function widget($args, $instance) {
    extract($args);
    extract($instance);
    $data = $this->get_api_call($args);
}

public function get_api_call($args) {
    $api = wp_remote_get("http://www.example.com/json/");
    $json_api = json_decode(stripslashes($api['body']));

    return $json_api;
}
}

This is a basic outline instance, you'll have to customize everything according to what you exactly need from here.