概要
woocommerce_settings_saved
は、WooCommerce設定が保存された際に発火するアクションフックです。このフックは、設定が変更された後に追加の機能を実装する際に非常に便利です。例えば、カスタムロジックを追加したり、特定のデータベース更新を行ったりします。
よく使われる機能の例としては以下が挙げられます:
- 設定変更後のデータのバリデーション
- カスタムログの記録
- 設定の後処理(例:メール送信)
- 他のデータベーステーブルへのデータ保存
- キャッシュのクリア
- APIへのデータ送信
構文
do_action( 'woocommerce_settings_saved' );
パラメータ
このアクションには特に渡されるデフォルトのパラメータはありませんが、関連する情報をフィルタリングすることは可能です。
戻り値
このアクションは戻り値を持ちません。
利用可能なバージョン
- WooCommerce: 2.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_settings_saved', 'log_woocommerce_settings' );
function log_woocommerce_settings() {
error_log( 'WooCommerce settings have been saved.' );
}
このサンプルでは、WooCommerceの設定が保存された際に、不具合の調査や記録のためにエラーログにメッセージを記録します。
サンプル2: 設定が保存された後にメールを送信する
add_action( 'woocommerce_settings_saved', 'send_settings_saved_email' );
function send_settings_saved_email() {
$to = 'admin@example.com';
$subject = 'WooCommerce Settings Updated';
$message = 'Your WooCommerce settings have been saved.';
wp_mail( $to, $subject, $message );
}
このコードは、WooCommerceの設定が保存された後に管理者にメールを送信します。
サンプル3: カスタム設定を保存する
add_action( 'woocommerce_settings_saved', 'save_custom_setting' );
function save_custom_setting() {
if ( isset( $_POST['custom_setting'] ) ) {
update_option( 'custom_setting', sanitize_text_field( $_POST['custom_setting'] ) );
}
}
このサンプルでは、フォームからカスタム設定が送信された場合に、その値をデータベースに保存します。
サンプル4: 設定変更に伴うキャッシュクリア
add_action( 'woocommerce_settings_saved', 'clear_cache_after_settings_saved' );
function clear_cache_after_settings_saved() {
if ( function_exists( 'wp_cache_flush' ) ) {
wp_cache_flush();
}
}
このコードは、WooCommerce設定が保存された際にキャッシュをクリアします。これにより、最新の設定が反映されます。
サンプル5: 他のテーブルにデータを保存する
add_action( 'woocommerce_settings_saved', 'save_data_to_custom_table' );
function save_data_to_custom_table() {
global $wpdb;
$data = array( 'setting_value' => 'some_value' );
$wpdb->insert( 'custom_table', $data );
}
このサンプルでは、WooCommerceの設定が保存された後に、カスタムデータベーステーブルにデータを保存しています。
これらのサンプルは、woocommerce_settings_saved
アクションを使って、WooCommerceの設定変更後に実行される処理の例を示しています。