向购物车中添加特定产品时如何删除特定购物车项目? [英] How to remove a specific cart item when adding to cart a specific product?

查看:93
本文介绍了向购物车中添加特定产品时如何删除特定购物车项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用WooCommerce,我想看看是否有可能从购物车中删除特定商品,如果购物车中还有其他特定商品。

With WooCommerce, I am looking to see if it's possible to remove a specific item (from cart), if another specific item is in the cart.

我的网站商店提供产品的免费版本,使客户可以基本访问网站内容。付费版本将打开对内容的更多访问。这样,如果免费版本已经在购物车中,并且付费版本已添加到购物车,则免费版本将从购物车中删除。

My web shop has a free version of a product which gives to customer a basic access to site content. The paid version will open up more access to content. This way if the free version is already in the cart, and the paid version gets added to cart, then the free version will be removed from cart.

我尝试查看可能的选项和插件,但是其中大多数都有基于价格和类似条件的条件。

I tried looking at possible options and plugins but most of them have conditions based on pricing and things like that.

推荐答案

使用自定义功能可以实现钩在例如 woocommerce_add_to_cart 钩中:

Yes is possible with a custom function hooked for example in woocommerce_add_to_cart hook:

add_action( 'woocommerce_add_to_cart', 'check_product_added_to_cart', 10, 6 );
function check_product_added_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {

    // Set HERE your targeted product ID
    $target_product_id = 31;
    // Set HERE the  product ID to remove
    $item_id_to_remove = 37;

    // Initialising some variables
    $has_item = false;
    $is_product_id = false;

    foreach( WC()->cart->get_cart() as $key => $item ){
        // Check if the item to remove is in cart
        if( $item['product_id'] == $item_id_to_remove ){
            $has_item = true;
            $key_to_remove = $key;
        }

        // Check if we add to cart the targeted product ID
        if( $product_id == $target_product_id ){
            $is_product_id = true;
        }
    }

    if( $has_item && $is_product_id ){
        WC()->cart->remove_cart_item($key_to_remove);

        // Optionaly displaying a notice for the removed item:
        wc_add_notice( __( 'The product "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
    }
}

此代码在function.php文件中

此代码已经过测试并且可以正常工作。

This code is tested and works.

这篇关于向购物车中添加特定产品时如何删除特定购物车项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆