2016-08-14 29 views
0

我想對需要呈現Wordpress頁面/窗口小部件中的數據的站點進行簡單的api調用。在Wordpress頁面和窗口小部件中進行簡單的Rest API調用

我創建了一個新的頁面,並把這個代碼編輯器對話框上我的控制面板:

<?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); 
?> 

沒有被呈現在我的WordPress的UI。

是的,我在我的本地環境(使用MAMP)。

回答

0

解決方案:

在你的插件目錄下創建一個文件夾,並創建將包含您的API調用PHP文件。

你看起來就會像這樣:

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; 
} 
} 

這是一個基本的輪廓實例,你必須根據你恰好從這裏需要定製的一切。

相關問題