dsf6565 2019-03-24 21:39
浏览 114
已采纳

根据特定产品有条不紊地删除Woocommerce购物车商品

A specific WooCommerce product can only be by itself in the cart.

So how do I clear the cart while adding this specific product to the cart? and how can I remove this specific product from the cart when adding any other product?

I've figured out how to empty the cart when adding a specific product but I don't know how to remove this specific product from the cart when adding any other product.

  • 写回答

2条回答 默认 最新

  • doufu8887 2019-03-25 03:52
    关注

    The following will remove conditionally cart items based on a specific product:

    • When the specific product is added to cart, all other items are removed.
    • When any other product is added to cart, it removes the specific product (if it's in cart)

    Here is the code:

    // Remove conditionally cart items based on a specific product (item)
    add_action( 'woocommerce_before_calculate_totals', 'remove_cart_items_conditionally', 10, 1 );
    function remove_cart_items_conditionally( $cart ) {
        // HERE define your specific product ID
        $specific_product_id = 37; 
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $cart_items  = $cart->get_cart(); // Cart items array
        $items_count = count($cart_items); // Different cart items count
    
        // Continue if cart has at least 2 different cart items
        if ( $items_count < 2 )
            return;
    
        $last_item    = end($cart_items); // Last cart item data array
        $is_last_item = false; // Initializing
    
        // Check if the specific product is the last added item
        if ( in_array($specific_product_id, array( $last_item['product_id'], $last_item['variation_id'] ) ) ) {
            $is_last_item = true;
        }
    
        // Loop through cart items
        foreach ( $cart_items as $cart_item_key => $cart_item ) {
            // Remove all others cart items when specific product ID is the last added to cart
            if ( ! in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && $is_last_item ) {
                $cart->remove_cart_item( $cart_item_key );
            }
            // Remove the specific item when its is not the last added to cart
            elseif ( in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && ! $is_last_item ) {
                $cart->remove_cart_item( $cart_item_key );
            }
        }
    }
    

    Code goes on function.php file of your active child theme (or active theme). Tested and works.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部