Php Woocomece在向购物车添加其他特定项目时删除特定购物车项目

Php Woocomece在向购物车添加其他特定项目时删除特定购物车项目,php,wordpress,woocommerce,product,cart,Php,Wordpress,Woocommerce,Product,Cart,这里提供的解决方案适用于一个产品id 有没有办法对多个id执行此操作?更新2:以下代码适用于多个产品id: 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_da

这里提供的解决方案适用于一个产品id


有没有办法对多个id执行此操作?

更新2:以下代码适用于多个产品id:

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_ids1 = array(31, 32);
    $target_product_ids2 = array(33, 34);
    // Set HERE the  product ID to remove
    $item_id_to_remove1 = 37;
    $item_id_to_remove2 = 53;

    // Initialising some variables
    $has_item1 = $has_item2 = $is_product_id1 = $is_product_id2 = false;

    foreach( WC()->cart->get_cart() as $key => $item ){
        // Check if the item to be removed 1 is in cart
        if( $item['product_id'] == $item_id_to_remove1 ){
            $has_item1 = true;
            $key_to_remove1 = $key;
        }
        // Check if the item to be removed 2 is in cart
        if( $item['product_id'] == $item_id_to_remove2 ){
            $has_item2 = true;
            $key_to_remove2 = $key;
        }

        // Check if we added to cart any targeted product IDs 1
        if( in_array( $product_id, $target_product_ids1 ) ){
            $is_product_id1 = true;
        }

        // Check if we added to cart any targeted product IDs 2
        if( in_array( $product_id, $target_product_ids2 ) ){
            $is_product_id2 = true;
        }
    }

    if( $has_item1 && $is_product_id1 ){
        WC()->cart->remove_cart_item($key_to_remove1);

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

    if( $has_item2 && $is_product_id2 ){
        WC()->cart->remove_cart_item($key_to_remove2);

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

代码进入活动子主题(或活动主题)的function.php文件。已测试且有效。

如果$target\u product\u id=31删除$product\u to\u remove=32,如果$target\u product\u id=33删除$product\u to\u remove=33等等,Hi是任何一种方法。谢谢you@DeividasKrupstas我已经更新了答案,有一个小错误。嗨,在购物车页面上,我有交叉销售的产品,如果我将其添加到购物车wc_添加_通知不起作用。但是,如果我从产品页面wc_add_notice添加了相同的产品,那么效果如何?您好,如果将某个产品(例如100)添加到购物车中,您将如何删除多个产品(例如ID 200和ID 300)?