Wordpressのプラグイン中で外部API等へヘッダにAuthorization入れたHTTPリクエストする

Wordpressで独自のプラグインを作成しているときに、そのプラグイン中から外部のAPIなどにHTTPリクエストをする際にWordpressでは以下の様なHTTP APIのヘルパー関数が用意されているのでリクエストを発行できる。

例えばGETリクエストであれば、 wp_remote_get() という関数があるのでこちらを利用すればよい。

外部で公開されているAPIなどで認証のためにリクエストヘッダに Authorization を含める必要がある場合もこの関数の第二引数でヘッダを指定することができるのでそこを指定することで解決できる。

<?php
$token = "(API request token)";
$url = "https://api.hogehoge.jp/v1/bar/123.json";
$response = wp_remote_get($url, array('headers' => array('Authorization' => "Bearer ". $token)));

こうすると以下の様なレスポンスが得られる。

array (size=6)
  'headers' => 
    object(Requests_Utility_CaseInsensitiveDictionary)[610]
      protected 'data' => 
        array (size=11)
          'server' => string 'nginx/1.4.4'
          'date' => string 'Sat, 07 Jan 2017 12:47:42 GMT'
          'content-type' => string 'application/json; charset=utf-8'
          'status' => string '200 OK'
          'x-frame-options' => string 'SAMEORIGIN'
          'x-xss-protection' => string '1; mode=block'
          'x-content-type-options' => string 'nosniff'
          'x-request-id' => string '5f1d6608-8e5f-4fee-b584-90ffb230ece9'
          'x-runtime' => string '0.056044'
  'body' => string '{.....}'... (length=4209)
  'response' => 
    array (size=2)
      'code' => int 200
      'message' => string 'OK' (length=2)
  'cookies' => 
    array (size=0)
      empty
  'filename' => null
  'http_response' => 
    object(WP_HTTP_Requests_Response)[606]

(snip)

レスポンスヘッダを始めとして必要な要素は全て得ることができる。

あとは必要に応じてbodyに含まれる文字列要素を操作すればよい。