首页 文章

当特定产品类别的商品在Woocommerce的购物车中时禁用购物

提问于
浏览
0

我试图禁用购物,如果某个特定产品类别的商品在购物车中(这是一个带有标签的产品形式的订阅 - 结帐和运送被剥离) . 将该产品添加到购物车时,不允许添加其他产品 .

我试过那些线程代码:

但没有帮助 .

如果特定产品类别在Woocommerce的购物车中,我该如何禁用购物?

output problem image

1 回答

  • 3

    2018年10月 - 改进的更新代码版本:禁用Woocommerce中特定类别的购物车项目的其他产品类别

    请尝试以下代码:

    • 当特定产品类别的产品在购物车中时,避免添加到购物车

    • 将特定产品类别的产品添加到购物车时,删除其他购物车项目

    代码:

    // Remove other items when our specific product is added to cart
    add_action( 'woocommerce_add_to_cart', 'remove_other_products_on_add_to_cart', 10, 6 );
    function remove_other_products_on_add_to_cart ( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
        // HERE set your product category (can be term IDs, slugs or names)
        $category = 'posters';
    
        // We remove other items when our specific product is added to cart
        if( has_term( $category, 'product_cat', $product_id ) ) {
            foreach( WC()->cart->get_cart() as $item_key => $cart_item ){
                if( ! has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
                    WC()->cart->remove_cart_item( $item_key );
                }
            }
        }
    }
    
    // Avoid other items to be added to cart when our specific product is in cart
    add_filter( 'woocommerce_add_to_cart_validation', 'check_and_limit_cart_items', 10, 3 );
    function check_and_limit_cart_items ( $passed, $product_id, $quantity ){
        // HERE set your product category (can be term IDs, slugs or names)
        $category = 'posters';
    
        // We exit if the cart is empty
        if( WC()->cart->is_empty() )
            return $passed;
    
        // CHECK CART ITEMS: search for items from product category
        foreach ( WC()->cart->get_cart() as $cart_item ){
            if( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
                // Display an warning message
                wc_add_notice( __('A subscription is already in cart (Other items are not allowed in cart).', 'woocommerce' ), 'error' );
                // Avoid add to cart
                return false;
            }
        }
        return $passed;
    }
    

    代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .

相关问题