概要
wp_remote_post
関数は、WordPressのHTTP APIの一部であり、リモートサーバーに対してPOSTメソッドを使用してリクエストを送信するために使われます。この関数は、外部APIとの連携やデータの送受信など、多くのシナリオで利用されます。具体的には、以下のような機能実装に使われることが多いです。
- 外部APIからのデータ収集
- フォームデータの送信
- 他のサービスへの情報登録
- Webhookとの連携
- サードパーティサービスとの認証
- データベースのバックアップ先への転送
- 定期的なデータ更新
- サーバー間のデータ同期
構文
$response = wp_remote_post( $url, $args );
パラメータ
$url
(string) : リクエストを送信する先のURL。$args
(array) : リクエストに関するオプション設定。
戻り値
- 成功した場合は、HTTPレスポンスの配列。失敗した場合は
WP_Error
オブジェクト。
関連する関数
使用可能なバージョン
wp_remote_post
関数は、WordPress 2.7.0以降で利用可能です。
コアファイルのパス
wp-includes/http.php
サンプルコード
サンプル1: 簡単なPOSTリクエスト
$response = wp_remote_post( 'https://example.com/api', array(
'body' => array( 'key' => 'value' ),
) );
if ( is_wp_error( $response ) ) {
echo 'エラー: ' . $response->get_error_message();
} else {
echo 'レスポンス: ' . wp_remote_retrieve_body( $response );
}
このサンプルコードは、指定したURLに対してシンプルなPOSTリクエストを送り、成功した場合はレスポンスを出力します。
サンプル2: カスタムヘッダーを追加するPOSTリクエスト
$response = wp_remote_post( 'https://example.com/api', array(
'headers' => array( 'Authorization' => 'Bearer your_token' ),
'body' => json_encode( array( 'data' => 'value' ) ),
'timeout' => 15,
) );
if ( is_wp_error( $response ) ) {
echo 'エラー: ' . $response->get_error_message();
} else {
echo 'レスポンス: ' . wp_remote_retrieve_body( $response );
}
このサンプルでは、認証用のカスタムヘッダーを追加してPOSTリクエストを送信します。
サンプル3: タイムアウトを設定したPOSTリクエスト
$response = wp_remote_post( 'https://example.com/api', array(
'body' => array( 'key' => 'value' ),
'timeout' => 10,
) );
if ( is_wp_error( $response ) ) {
echo 'エラー: ' . $response->get_error_message();
}
このサンプルでは、リクエストのタイムアウト時間を設定しています。
サンプル4: コールバック関数を使ったPOSTリクエスト
$response = wp_remote_post( 'https://example.com/api', array(
'body' => array( 'key' => 'value' ),
'timeout' => 10,
'cookies' => $_COOKIE,
) );
if ( is_wp_error( $response ) ) {
echo 'エラー: ' . $response->get_error_message();
}
このサンプルでは、クッキーを送信しながらPOSTリクエストを行います。
サンプル5: JSONデータを送信するPOSTリクエスト
$response = wp_remote_post( 'https://example.com/api', array(
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => json_encode( array( 'key' => 'value' ) ),
) );
if ( is_wp_error( $response ) ) {
echo 'エラー: ' . $response->get_error_message();
} else {
echo 'レスポンス: ' . wp_remote_retrieve_body( $response );
}
このサンプルでは、JSON形式のデータを送信するためにContent-Typeヘッダーを設定しています。
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |
この関数は特定のバージョンで非推奨や削除されていません。