概要
woocommerce_pre_payment_complete
アクションは、WooCommerceにおいて、支払いが完了する前のタイミングでトリガーされるフックです。このアクションを使用することで、支払い処理が完了する前のステージでさまざまなカスタム処理を実行できるようになります。具体的には次のような用途でよく使われます。
- 追加のデータ検証
- クーポンやポイントの適用
- 外部APIへの通知
- ロギングやトラッキング
- ユーザーへのカスタムメッセージ表示
- 購入制限のチェック
構文
add_action('woocommerce_pre_payment_complete', 'your_custom_function', 10, 1);
パラメータ
$order_id
(int): 注文IDが渡されます。
戻り値
このアクション自体は戻り値を持ちませんが、関連する処理の結果を処理するためのカスタム関数を利用することができます。
使用可能なバージョン
- WooCommerce: 3.0.0以上
- WordPress: 4.0.0以上
サンプルコード
サンプルコード1: 注文のカスタムメタデータを追加
このコードは、支払いが完了する前に注文にカスタムメタデータを追加します。
add_action('woocommerce_pre_payment_complete', 'add_custom_meta_to_order', 10, 1);
function add_custom_meta_to_order($order_id) {
$order = wc_get_order($order_id);
$order->update_meta_data('custom_meta_key', 'custom_value');
$order->save();
}
サンプルコード2: 外部APIへの通知
このコードは、支払いが完了する前に外部APIに通知を送信する例です。
add_action('woocommerce_pre_payment_complete', 'notify_external_api', 10, 1);
function notify_external_api($order_id) {
$order = wc_get_order($order_id);
$response = wp_remote_post('https://api.example.com/notify', [
'body' => [
'order_id' => $order->get_id(),
'total' => $order->get_total(),
],
]);
}
サンプルコード3: クーポンの適用確認
このコードは、クーポンの適用が正しく行われているかどうかを確認するためのものです。
add_action('woocommerce_pre_payment_complete', 'check_coupon_validity', 10, 1);
function check_coupon_validity($order_id) {
$order = wc_get_order($order_id);
if ($order->get_used_coupons()) {
// ここにカスタム処理を追加
}
}
サンプルコード4: ユーザーへのカスタムメッセージ
このコードは、支払いが完了する前にユーザーにカスタムメッセージを表示する例です。
add_action('woocommerce_pre_payment_complete', 'display_custom_message', 10, 1);
function display_custom_message($order_id) {
$order = wc_get_order($order_id);
wc_add_notice(__('Thank you for your order! You will receive an email confirmation shortly.'), 'notice');
}
サンプルコード5: ロギングの追加
このコードは、支払いプロセスのログをファイルに記録するためのものです。
add_action('woocommerce_pre_payment_complete', 'log_payment_process', 10, 1);
function log_payment_process($order_id) {
$order = wc_get_order($order_id);
$log_message = 'Payment processing started for Order ID: ' . $order_id;
error_log($log_message);
}
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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 |