wp_remote_get()


WordPress関数wp_remote_get()は、HTTP GETリクエストを送信し、リモートサーバーからデータを取得するために使用されます。この関数は、外部APIと連携する際によく使用されます。

シンタックス

wp_remote_get( string $url, array $args = array() );

引数の説明:

  • $url (string) — データを取得する対象のURL。
  • $args (array) — HTTPリクエストのオプションを設定する連想配列。

主な$argsのキー:

  • timeout (int) — リクエストがタイムアウトするまでの秒数。デフォルトは15秒。
  • headers (array) — HTTPヘッダーを設定する配列。
  • body (mixed) — リクエストの本文。
  • cookies (array) — クッキーを設定する配列。

例1: 基本的なGETリクエスト

リモートサーバーからデータを取得します。

$response = wp_remote_get( 'https://example.com/api/data' );

例2: タイムアウトを設定したリクエスト

10秒でタイムアウトするリクエストを送信します。

$response = wp_remote_get( 'https://example.com/api/data', array( 'timeout' => 10 ) );

例3: ヘッダーを設定したリクエスト

カスタムHTTPヘッダーを使用してリクエストを送信します。

$response = wp_remote_get( 'https://example.com/api/data', array( 'headers' => array( 'Authorization' => 'Bearer your-token' ) ) );

例4: データを取得し結果を解析

レスポンスボディを取得し、JSON形式で解析します。

$response = wp_remote_get( 'https://example.com/api/data' );
if ( is_wp_error( $response ) ) { return; }
$data = json_decode( wp_remote_retrieve_body( $response ), true );

例5: クッキーを設定してリクエスト

特定のクッキーを使用してリクエストを送信します。

$response = wp_remote_get( 'https://example.com/api/data', array( 'cookies' => array( new WP_Http_Cookie( array( 'name' => 'example', 'value' => '12345' ) ) ) ) );

注意事項

  • wp_remote_get()を使用する際は、SSL/TLSが有効なURLを優先的に利用してください。
  • レスポンスのエラーチェックを必ず行い、不正なデータ処理を防止してください。
  • 大量のリクエストを行う場合は、サーバーの負荷に注意してください。

関連機能: