概要
woocommerce_save_account_detailsアクションは、WooCommerceのアカウント詳細が保存されたときに発火します。このフックを利用することで、アカウント情報の更新時に様々な処理を追加できます。一般的にこのアクションは、以下のような機能を実装する際に使用されます。
- ユーザーのデータをログに記録する
- パスワード変更時に通知を送る
- カスタムフィールドの更新
- 追加のバリデーションチェック
- ユーザーにカスタムメッセージを表示する
- 他のシステムとデータを同期する
構文
do_action( 'woocommerce_save_account_details', $user_id, $request );
パラメータ
$user_id(int): 現在のユーザーのID$request(array): 更新されたアカウント情報の配列
戻り値
このアクションは戻り値を持たず、主に他の関数を呼び出すために使用されます。
使用可能なバージョン
- WooCommerce: バージョン 2.1 以降
- 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_save_account_details', 'log_account_details_change', 10, 2 );
function log_account_details_change( $user_id, $request ) {
error_log( 'User with ID ' . $user_id . ' has updated their account details.' );
}
引用元: WordPress.org
サンプル2: パスワード変更時に通知を送る
このコードは、ユーザーがパスワードを更新したときにメール通知を送ります。
add_action( 'woocommerce_save_account_details', 'send_password_change_notification', 10, 2 );
function send_password_change_notification( $user_id, $request ) {
if ( ! empty( $request['password_1'] ) ) {
// Send notification email
wp_mail( get_option( 'admin_email' ), 'Password Changed', 'User with ID ' . $user_id . ' has changed their password.' );
}
}
引用元: WordPress.org
サンプル3: カスタムフィールドの更新
このサンプルは、ユーザーが更新したカスタムフィールドを保存します。
add_action( 'woocommerce_save_account_details', 'update_custom_fields', 10, 2 );
function update_custom_fields( $user_id, $request ) {
if ( isset( $request['custom_field'] ) ) {
update_user_meta( $user_id, 'custom_field', sanitize_text_field( $request['custom_field'] ) );
}
}
引用元: WordPress.org
サンプル4: バリデーションチェック
このコードは、アカウント情報が保存される前に追加のバリデーションを行います。
add_action( 'woocommerce_save_account_details', 'add_validation_check', 10, 2 );
function add_validation_check( $user_id, $request ) {
if ( empty( $request['billing_first_name'] ) ) {
wc_add_notice( 'First name is required.', 'error' );
}
}
引用元: WordPress.org
サンプル5: カスタムメッセージの表示
アカウント情報が更新された後にカスタムメッセージを表示するサンプルです。
add_action( 'woocommerce_save_account_details', 'display_custom_message', 10, 2 );
function display_custom_message( $user_id, $request ) {
wc_add_notice( 'Your account details have been successfully updated.', 'success' );
}
引用元: WordPress.org