如何转换和使用远程WordPress服务器上的JSON数据?

时间:2017-02-04 作者:john-thomas

我有这个密码

add_action( \'init\', \'check_api_data\' );

function check_api_data() {    

  if(isset($_GET[\'api\']) ) {
  if ($_GET[\'api\'] == \'json\'){
           $args = array(  
                \'post_type\' => \'post\'
           );
           $query = new WP_Query( $args ); // $query is the WP_Query Object
           $posts = $query->get_posts();   // $posts contains the post objects

           $output = array();
           foreach( $posts as $post ) {    // Pluck the id and title attributes
               $output[] = array( 
                \'id\' => $post->ID, 
                \'title\' => $post->post_title, 
                \'content\' => $post ->post_content,
                \'imageurl\' => wp_get_attachment_url( get_post_thumbnail_id($post->ID) )
                );
           }
           header("Content-type: application/json");
           echo json_encode( $output );
       }
   exit();
   }  
}
这是输出:

[
  {
    "id": 19,
    "title": "Early bird tickets",
    "content": "that is good",
    "imageurl": "http://localhost/PRACTISE/wp/wp-content/uploads/2016/10/news2.jpg"
  },
  {
    "id": 95,
    "title": "See you next year!",
    "content": "Lorem ipsum",
    "imageurl": "http://localhost/PRACTISE/wp/wp-content/uploads/2016/11/tak_for_i_aar.jpg"
  }
]
如何在远程服务器中使用这些数据,以便每次我更新服务器a的内容时,它都会在服务器B上更新

1 个回复
最合适的回答,由SO网友:KAGG Design 整理而成

在服务器B上:

$result = wp_remote_post(\'http://serverA.com/?api=json\', array(
    \'method\'      => \'POST\',
    \'redirection\' => 1,
    \'httpversion\' => \'1.0\',
    \'blocking\'    => true,
    \'headers\'     => array(),
    \'body\'        => array(),
    \'cookies\'     => array()
));
if ( is_wp_error( $result ) ) {
    return \'bad connection!\';
}
$json = $result[\'body\'];
$posts = json_decode($json);
现在您有了$posts,就像php数组一样。var_dump($posts) 将看起来像:

array(2) {
  [0]=>
  object(stdClass)#7918 (4) {
    ["id"]=>
    int(19)
    ["title"]=>
    string(18) "Early bird tickets"
    ["content"]=>
    string(12) "that is good"
    ["imageurl"]=>
    string(65) "http://localhost/PRACTISE/wp/wp-content/uploads/2016/10/news2.jpg"
  }
  [1]=>
  object(stdClass)#7919 (4) {
    ["id"]=>
    int(95)
    ["title"]=>
    string(18) "See you next year!"
    ["content"]=>
    string(11) "Lorem ipsum"
    ["imageurl"]=>
    string(73) "http://localhost/PRACTISE/wp/wp-content/uploads/2016/11/tak_for_i_aar.jpg"
  }
}

相关推荐

使用帖子标题搜索WP API

我正在使用WP REST API v2尝试搜索具有相同标题的所有帖子,我尝试的是为两个团队创建一种“面对面/以前的会议”页面。目前我可以用一个弹头收回一个帖子,没问题.../wp-json/sportspress/v2/events?slug=team1-vs-team2 当我使用搜索时,它会检索team1和team2的所有事件,以及对team1的所有引用;2来自帖子内容,这不是我想要的。。。.../wp-json/sportspress/v2/events?search=team1+team2