且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将特定产品添加到购物车时如何删除特定的购物车项目?

更新时间:2023-10-25 15:24:58

是的,例如在 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.