概要
woocommerce_settings_save_$CURRENT_TAB
アクションは、WooCommerceの設定ページで特定のタブが保存されたときに発火するフックです。このフックは、WooCommerceの設定を変更する際にカスタム処理を追加する用途でよく使用されます。以下のような機能実装に役立つことがあります。
- 設定値の検証
- 設定のデフォルト値の設定
- カスタムメッセージの表示
- 特定の条件に基づく追加設定の保存
- 他のプラグインとの連携
- 外部サービスへのデータ送信
構文
do_action( "woocommerce_settings_save_{$current_tab}" );
パラメータ
$current_tab
: 現在のタブのスラッグ名。
戻り値
- 「戻り値」はありません。アクションフックのため、特定の戻り値はなく、他の関数が呼び出されることで処理を実行します。
使用可能なバージョン
- WooCommerce: 3.0以降
- WordPress: 4.0以降
サンプルコード
サンプル1: 設定値の検証
add_action('woocommerce_settings_save_general', 'validate_custom_settings');
function validate_custom_settings($current_tab) {
if (isset($_POST['custom_field']) && empty($_POST['custom_field'])) {
add_settings_error('general', 'custom_field_error', __('Custom field cannot be empty.'));
}
}
このコードは、一般設定タブを保存する際、カスタムフィールドが空である場合にエラーメッセージを追加します。
サンプル2: メッセージの表示
add_action('woocommerce_settings_save_checkout', 'display_message_after_save');
function display_message_after_save($current_tab) {
echo '<div class="updated"><p>' . __('Settings saved successfully.', 'woocommerce') . '</p></div>';
}
このコードは、チェックアウト設定を保存した後に「設定が正常に保存されました」とのメッセージを表示します。
サンプル3: 外部APIへのデータ送信
add_action('woocommerce_settings_save_products', 'send_data_to_external_api');
function send_data_to_external_api($current_tab) {
// APIにデータを送信するロジックを追加
wp_remote_post('https://example.com/api/save', [
'body' => json_encode($_POST),
'headers' => ['Content-Type' => 'application/json']
]);
}
このコードは、製品設定が保存された後に外部APIにデータを送信します。
サンプル4: デフォルト値の設定
add_action('woocommerce_settings_save_tax', 'set_default_tax_settings');
function set_default_tax_settings($current_tab) {
if (!isset($_POST['tax_default'])) {
update_option('woocommerce_tax_default', '0'); // デフォルト値を設定
}
}
このコードは、税設定が保存された際に特定のオプションのデフォルト値を設定します。
サンプル5: 追加設定の保存
add_action('woocommerce_settings_save_shipping', 'save_custom_shipping_settings');
function save_custom_shipping_settings($current_tab) {
if (isset($_POST['custom_shipping_option'])) {
update_option('woocommerce_custom_shipping_option', sanitize_text_field($_POST['custom_shipping_option']));
}
}
このコードは、配送設定タブでカスタムオプションが保存された際、オプションの値をデータベースに保存します。
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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 |