1

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).

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.