You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce购物车:无需钩子获取已移除特定商品的购物车项Key ID

WooCommerce自定义cart.php中获取移除商品Key ID的解决方案

无法仅从移除提示文本"Item X" removed. Undo?中获取已移除商品的唯一Key ID,原因如下:

  • 提示文本是前端展示用的本地化文案,仅包含商品名称,未嵌入任何后台唯一标识数据;
  • 不同商品可能重名,靠名称无法精准定位到唯一购物车商品项,更无法获取Key ID。

不依赖钩子的可行方案(基于自定义cart.php模板)

  1. 在移除按钮中嵌入商品标识数据
    在渲染购物车商品移除按钮时,将商品的cart_item_key和商品类型通过HTML自定义属性嵌入:

    // 自定义cart.php中渲染移除按钮的代码段
    $cart_item_key = $cart_item['key'];
    $product = $cart_item['data'];
    $product_type = $product->get_type();
    
    echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
        '<a href="%s" class="remove" aria-label="%s" data-item-key="%s" data-product-type="%s">&times;</a>',
        esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
        esc_attr__( 'Remove this item', 'woocommerce' ),
        esc_attr( $cart_item_key ),
        esc_attr( $product_type )
    ), $cart_item_key );
    
  2. 前端通过JS获取标识并处理逻辑
    用户点击移除按钮时,通过JS读取自定义属性值,根据商品类型执行后续操作:

    document.querySelectorAll('.woocommerce-cart .remove').forEach(btn => {
        btn.addEventListener('click', function() {
            const itemKey = this.dataset.itemKey;
            const productType = this.dataset.productType;
    
            // 根据商品类型执行对应逻辑
            if (productType === 'subscription') {
                console.log('移除的是订阅商品,Key ID:', itemKey);
                // 这里添加你的后续处理代码
            }
        });
    });
    

补充:更可靠的钩子方案(推荐)

如果需要在后端处理移除后的逻辑,建议使用WooCommerce原生钩子woocommerce_cart_item_removed,直接获取商品关键数据:

add_action('woocommerce_cart_item_removed', 'handle_removed_cart_item', 10, 2);
function handle_removed_cart_item($cart_item_key, $cart) {
    $cart_item = $cart->get_cart_item($cart_item_key);
    if (!$cart_item) return;

    $product_type = $cart_item['data']->get_type();
    // 根据商品类型执行后续逻辑
    if ($product_type === 'variable') {
        // 处理可变商品移除后的操作
    }
}

内容的提问来源于stack exchange,提问作者Greg Bialowas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 10:07:24