概要
woocommerce_cart_item_removed
アクションフックは、WooCommerceにおいてカートからアイテムが削除されたときに発火します。このフックは、カートアイテムが削除された際に特定の処理を実行するためによく使用されます。具体的には、以下のような機能を実装する際に役立ちます。
- カート削除時のカスタムメッセージの表示
- 削除されたアイテムに関連するクーポンの無効化
- 在庫の更新処理
- 削除されたアイテムに基づくユーザー行動の追跡
- メール通知やアラートの送信
- アナリティクスツールとの統合
構文
add_action('woocommerce_cart_item_removed', 'your_custom_function', 10, 2);
パラメータ
$cart_item_key
– 削除されたアイテムのカートキー。$cart
– 現在のカートの内容を含む配列。
戻り値
このアクションには戻り値はありません。
使用可能なバージョン
- WooCommerce: 2.0 以上
- WordPress: 3.0 以上
サンプルコード
サンプルコード1: 削除時の通知メッセージを表示
このコードは、カートからアイテムが削除されたときに通知メッセージを表示します。
add_action('woocommerce_cart_item_removed', 'notify_item_removed', 10, 2);
function notify_item_removed($cart_item_key, $cart) {
wc_add_notice('アイテムがカートから削除されました。', 'notice');
}
引用元: https://developer.woocommerce.com/
サンプルコード2: 削除されたアイテムで関連するクーポンを無効にする
このコードは、特定のアイテムがカートから削除された際に、関連するクーポンを無効にします。
add_action('woocommerce_cart_item_removed', 'disable_coupon_on_item_removal', 10, 2);
function disable_coupon_on_item_removal($cart_item_key, $cart) {
$removed_item = $cart[$cart_item_key];
if ($removed_item['product_id'] == 123) { // 商品ID 123 に関連するクーポンを無効
WC()->cart->remove_coupons('discount_coupon_code');
}
}
引用元: https://woothemes.com/
サンプルコード3: 在庫の更新
このコードはカートからアイテムが削除されたときに在庫を更新します。
add_action('woocommerce_cart_item_removed', 'update_stock_on_item_removal', 10, 2);
function update_stock_on_item_removal($cart_item_key, $cart) {
$removed_item = $cart[$cart_item_key];
$product = wc_get_product($removed_item['product_id']);
if ($product) {
$product->increase_stock(1); // 在庫を増やす
}
}
引用元: https://wordpress.stackexchange.com/
サンプルコード4: Googleアナリティクスのイベントを送信
削除されたアイテムに関するデータをGoogleアナリティクスに送信することができます。
add_action('woocommerce_cart_item_removed', 'send_event_to_ga_on_removal', 10, 2);
function send_event_to_ga_on_removal($cart_item_key, $cart) {
$removed_item = $cart[$cart_item_key];
echo "<script> ga('send', 'event', 'Cart', 'Remove', '{$removed_item['data']->get_name()}'); </script>";
}
引用元: https://www.wpbeginner.com/
サンプルコード5: メール通知の送信
このコードは、カートからアイテムが削除されたときに特定のメールを送信します。
add_action('woocommerce_cart_item_removed', 'send_email_on_item_removal', 10, 2);
function send_email_on_item_removal($cart_item_key, $cart) {
$removed_item = $cart[$cart_item_key];
$to = 'admin@example.com';
$subject = 'カートアイテム削除通知';
$message = 'アイテムがカートから削除されました: ' . $removed_item['data']->get_name();
wp_mail($to, $subject, $message);
}
引用元: https://www.sitepoint.com/
この関数のアクションでの使用可能性
アクション名 | 使用可能性 |
---|---|
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 |