概要
woocommerce_save_settings_$CURRENT_TAB
アクションは、WooCommerceの設定が保存される際にトリガーされるフックです。このフックは、WordPressの管理画面内で特定のタブに関連する設定が保存された後に実行され、主に設定のデータを処理・保存する際に活用されます。このアクションは次のような状況でよく使われます。
- カスタム設定の検証
- フィールドのデータをデータベースに保存
- サードパーティサービスへのデータ送信
- 設定の変更に自身のビジネスロジックを追加
- 特定のユーザーに対する設定のカスタマイズ
- 設定保存後の通知やログ記録
構文
do_action( "woocommerce_save_settings_{$current_tab}" );
パラメータ
$current_tab
: 現在の設定タブの識別子(文字列)。
戻り値
このアクションは特に戻り値を持ちませんが、フックを利用する関数は通常、特定の処理結果を持つ場合があります。
WooCommerceのバージョン
- WooCommerce 3.0.0以降
WordPressのバージョン
- 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_settings_general', 'save_custom_general_settings' );
function save_custom_general_settings( $settings ) {
// カスタムフィールドのデータを保存
if ( isset( $_POST['custom_field'] ) ) {
update_option( 'custom_field', sanitize_text_field( $_POST['custom_field'] ) );
}
}
このサンプルコードは、WooCommerceの一般設定タブで「custom_field」というカスタムフィールドのデータを保存するためのものです。
サンプルコード2
add_action( 'woocommerce_save_settings_accounts', 'handle_account_settings' );
function handle_account_settings() {
if ( isset( $_POST['account_custom_option'] ) ) {
update_option( 'account_custom_option', sanitize_text_field( $_POST['account_custom_option'] ) );
}
}
このコードは、アカウント設定タブにおいてカスタムオプションのデータをデータベースに保存する役割を果たします。
サンプルコード3
add_action( 'woocommerce_save_settings_payment', 'log_payment_settings_changes' );
function log_payment_settings_changes() {
// 設定変更のログを記録
error_log( 'Payment settings have been saved.' );
}
このサンプルは、WooCommerceの支払い設定タブで設定が保存された際に、変更をログに記録します。
サンプルコード4
add_action( 'woocommerce_save_settings_shipping', 'validate_shipping_settings' );
function validate_shipping_settings() {
// 減算設定が有効かを検証
if ( ! isset( $_POST['shipping_calculator_enable'] ) ) {
add_settings_error( 'shipping_settings', 'shipping_error', 'Shipping calculator must be enabled.' );
}
}
このコードは、配送設定タブでいくつかの設定の検証を行い、エラーが存在する場合は適切なメッセージを表示します。
サンプルコード5
add_action( 'woocommerce_save_settings_products', 'notify_products_settings_saved' );
function notify_products_settings_saved() {
// 設定が保存された後に管理者に通知
if ( current_user_can( 'manage_options' ) ) {
add_action( 'admin_notices', function() {
echo '<div class="notice notice-success"><p>Product settings saved successfully!</p></div>';
});
}
}
このサンプルコードは、商品設定タブにおいて設定が正常に保存された際に、管理者に成功メッセージを表示します。