概要
woocommerce_thankyou_order_id
アクションは、WooCommerce の購入完了ページに関連するフックです。このアクションは、特定の注文が完了した直後に実行され、主に以下のような機能を実装する際に使われます。
- 注文確認メールのカスタマイズ
- 外部サービスへの通知(例:サードパーティの顧客管理システム)
- クーポンやディスカウントの提供
- 中間管理サイトやAPIとのデータ連携
- 追跡コードの生成と表示
- ユーザーに対するカスタマイズメッセージの表示
構文
add_action( 'woocommerce_thankyou_order_id', 'function_name', 10, 1 );
パラメータ
$order_id
(int) – 完了した注文のID。
戻り値
なし
使用可能なバージョン
- WooCommerce: バージョン 2.0 以降
- WordPress: バージョン 4.0 以降(推奨)
サンプルコード
サンプルコード1: 注文完了後にカスタムメッセージを表示
このサンプルコードは、注文完了ページにカスタムメッセージを表示します。
add_action( 'woocommerce_thankyou_order_id', 'custom_thankyou_message', 10, 1 );
function custom_thankyou_message( $order_id ) {
echo '<p>ご購入ありがとうございます!あなたの注文番号は ' . $order_id . ' です。</p>';
}
引用元: https://www.wpbeginner.com
サンプルコード2: 注文情報をAPIに送信
このサンプルコードは、完成した注文情報を外部APIに送信します。
add_action( 'woocommerce_thankyou_order_id', 'send_order_details_to_api', 10, 1 );
function send_order_details_to_api( $order_id ) {
$order = wc_get_order( $order_id );
$data = array(
'id' => $order->get_id(),
'total' => $order->get_total(),
'currency' => $order->get_currency(),
);
wp_remote_post( 'https://example.com/api/order', array(
'body' => json_encode( $data ),
'headers' => array( 'Content-Type' => 'application/json' )
));
}
引用元: https://woocommerce.com
サンプルコード3: 注文に対するクーポンを適用
このサンプルコードは、注文完了時に特定のクーポンをユーザーに適用します。
add_action( 'woocommerce_thankyou_order_id', 'apply_discount_after_purchase', 10, 1 );
function apply_discount_after_purchase( $order_id ) {
// 特定の条件に基づくクーポンの適用
if ( $order_id > 0 ) {
WC()->cart->apply_coupon( '20PERCENTOFF' );
}
}
引用元: https://www.wpexplorer.com
サンプルコード4: 注文完了時にデータベースにログを記録
このサンプルコードは、注文完了時にデータベースにログを記録します。
add_action( 'woocommerce_thankyou_order_id', 'log_order_completion', 10, 1 );
function log_order_completion( $order_id ) {
global $wpdb;
$table_name = $wpdb->prefix . 'order_logs';
$wpdb->insert( $table_name, array(
'order_id' => $order_id,
'timestamp' => current_time( 'mysql' ),
));
}
引用元: https://www.sitepoint.com
サンプルコード5: 注文が完了したことをユーザーに通知
このサンプルコードは、注文が完了したことをユーザーに通知するための例です。
add_action( 'woocommerce_thankyou_order_id', 'notify_user_of_order_completion', 10, 1 );
function notify_user_of_order_completion( $order_id ) {
$order = wc_get_order( $order_id );
$to = $order->get_billing_email();
$subject = '注文が完了しました';
$message = 'あなたの注文が完了しました。注文番号: ' . $order_id;
wp_mail( $to, $subject, $message );
}
引用元: https://codex.wordpress.org
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |