概要
woocommerce_checkout_update_customer_data
アクションは、WooCommerceのチェックアウトプロセスにおいて、顧客データが更新される際にトリガーされるフックです。このアクションを使うことで、カスタムフィールドの保存や、データベースの更新、メール通知の送信などのさまざまなカスタマイズが可能となります。具体的には、以下のような機能を実装する際に使われます。
- チェックアウトフォームにカスタムフィールドを追加する。
- 追加したカスタムフィールドからデータを取得し保存する。
- 顧客のロイヤルティプログラムに基づく更新を行う。
- フォームバリデーションを行う。
- 特定の条件に基づいてデータをフィルタリングする。
- チェックアウト後に外部サービスへデータを送信する。
構文
add_action('woocommerce_checkout_update_customer_data', 'your_custom_function', 10, 1);
パラメータ
$customer
(WC_Customer): 更新された顧客データを含むWC_Customerオブジェクト。
戻り値
このアクションは戻り値を持ちませんが、他の関数を利用してデータの変更を行うことができます。
使用可能なプラグインバージョン
- WooCommerce: バージョン 3.0 以上
- WordPress: バージョン 4.0 以上
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |
サンプルコード
サンプルコード 1: カスタムフィールドの保存
このコードは、チェックアウト時に追加されたカスタムフィールドのデータを保存します。
add_action('woocommerce_checkout_update_customer_data', 'save_custom_checkout_field', 10, 1);
function save_custom_checkout_field($customer) {
if (isset($_POST['custom_field'])) {
$customer->update_meta_data('custom_field', sanitize_text_field($_POST['custom_field']));
}
}
サンプルコード 2: メール通知の送信
このコードは、顧客データが更新された際にメール通知を送信します。
add_action('woocommerce_checkout_update_customer_data', 'send_email_on_checkout_update', 10, 1);
function send_email_on_checkout_update($customer) {
$to = $customer->get_billing_email();
$subject = 'Your account has been updated';
$message = 'Your account information has been updated during checkout.';
wp_mail($to, $subject, $message);
}
サンプルコード 3: フォームバリデーション
このコードは、カスタムフィールドが空でないかどうかをチェックします。
add_action('woocommerce_checkout_update_customer_data', 'validate_custom_field', 10, 1);
function validate_custom_field($customer) {
if (empty($_POST['custom_field'])) {
wc_add_notice(__('Please fill in the required custom field.'), 'error');
}
}
サンプルコード 4: データのフィルタリング
このコードは、特定の条件に基づいて顧客データをフィルタリングします。
add_action('woocommerce_checkout_update_customer_data', 'filter_customer_data', 10, 1);
function filter_customer_data($customer) {
if ($customer->get_billing_country() === 'US') {
$customer->update_meta_data('tax_exempt', 'yes');
}
}
サンプルコード 5: 外部サービスへのデータ送信
このコードは、チェックアウト後に顧客データを外部APIに送信します。
add_action('woocommerce_checkout_update_customer_data', 'send_data_to_external_service', 10, 1);
function send_data_to_external_service($customer) {
$data = array(
'email' => $customer->get_billing_email(),
'name' => $customer->get_first_name() . ' ' . $customer->get_last_name(),
);
$response = wp_remote_post('https://api.example.com/update-customer', array(
'method' => 'POST',
'body' => json_encode($data),
'headers' => array('Content-Type' => 'application/json'),
));
}
これらのサンプルコードは、WooCommerceのチェックアウトプロセスにおけるカスタマイズ方法を示しています。