从WooCommerce中的购物车中删除特定产品的变化

问题描述

我想从wordpress woocommerce的购物车中删除一个变体产品。

我可以删除一个简单的产品,但不能删除其他产品。 使用此代码,我可以删除一个简单的产品。 我尝试传递变体ID和父变体ID。 我不知道为什么它不起作用,如果有人知道了,我将不胜感激。

$product_cart_id = WC()->cart->generate_cart_id( $aCurrentUserDataItem->id );
$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );

解决方法

您还可以按照以下步骤使用foreach循环来定位并从购物车中删除特定的版本ID:

$remove_variation_id = 41; // The variation id to remove

// loop through cart items
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
    // If the targeted variation id is in cart
    if ( $item['variation_id'] == $remove_variation_id ) {
        WC()->cart->remove_cart_item( $item_key ); // we remove it
        break; // stop the loop
    }
}

经过测试可以正常工作。