概要
wp_remote_request関数は、WordPressにおけるHTTPリクエストを送信するための関数です。この関数は、APIとの通信や、外部のリソースからデータを取得する際などに広く使用されます。具体的には以下のような機能を実装する際によく使われます:
- 外部APIからデータを取得
- RESTfulサービスとの通信
- データを取得してプラグインに取り込む
- 非同期にサーバーから情報を取得
- サイト間で情報を送信
- 他のサービスからWebhookを受信
- 外部のデータソースとの連携
- 自動更新機能の実装
wp_remote_request関数は、特定のURLにHTTPリクエストを送信し、レスポンスを取得します。
構文
$response = wp_remote_request( $url, $args );
パラメータ
$url(string) – リクエスト先のURL$args(array) – (オプション)リクエストの引数。方法(GET/POSTなど)、ヘッダー、ボディなどを指定することができます。
戻り値
返り値は、HTTPレスポンスを表す配列か、WP_Errorオブジェクトです。成功した場合、レスポンスにはステータスコードやヘッダー、ボディが含まれます。
関連する関数
使用可能なバージョン
この関数は、WordPress 2.8.0以降で使用可能です。
コアファイルのパス
wp-includes/http.php
サンプルコード
サンプルコード1: GETリクエストを送信
$response = wp_remote_request( 'https://api.example.com/data', array( 'method' => 'GET' ) );
if( is_wp_error( $response ) ) {
echo 'Error: ' . $response->get_error_message();
} else {
$body = wp_remote_retrieve_body( $response );
echo $body;
}
説明: 外部APIからGETリクエストを送信し、エラーハンドリングを行い、レスポンスボディを出力します。
サンプルコード2: POSTリクエストを送信
$response = wp_remote_request( 'https://api.example.com/data', array(
'method' => 'POST',
'body' => json_encode( array( 'key' => 'value' ) ),
'headers' => array( 'Content-Type' => 'application/json' ),
) );
if( is_wp_error( $response ) ) {
echo 'Error: ' . $response->get_error_message();
} else {
$body = wp_remote_retrieve_body( $response );
echo $body;
}
説明: 外部APIにPOSTリクエストを送信し、JSON形式でデータを送信します。
サンプルコード3: レスポンスのステータスコードを取得
$response = wp_remote_get( 'https://api.example.com/data' );
if( ! is_wp_error( $response ) ) {
$response_code = wp_remote_retrieve_response_code( $response );
echo 'HTTP Response Code: ' . $response_code;
}
説明: GETリクエストを送り、HTTPレスポンスコードを取得して表示します。
サンプルコード4: リクエストのタイムアウト設定
$response = wp_remote_request( 'https://api.example.com/data', array(
'timeout' => 5, // タイムアウトを5秒に設定
) );
説明: リクエストのタイムアウトを5秒に指定して、外部APIにアクセスします。
サンプルコード5: カスタムヘッダーを付加してリクエスト
$response = wp_remote_request( 'https://api.example.com/data', array(
'method' => 'GET',
'headers' => array(
'Authorization' => 'Bearer YOUR_API_TOKEN',
),
) );
説明: GETリクエストにカスタムのAuthorizationヘッダーを追加して外部APIにアクセスします。
この関数のアクションでの使用可能性
| アクション | 使用可能性 |
|---|---|
| mu_plugin_loaded | |
| registered_post_type | |
| plugins_loaded | |
| wp_roles_init | |
| setup_theme | |
| after_setup_theme | |
| set_current_user | |
| init | 〇 |
| register_sidebar | |
| wp_loaded | 〇 |
| send_headers | |
| parse_query | |
| pre_get_posts | |
| wp | 〇 |
| template_redirect | |
| get_header | |
| wp_head |
この関数は特定のバージョンで非推奨または削除されていません。