I am trying to create a custom cart page function which first goes through all the 'already added to cart items', but based on some conditions picks and populates the cart page with only some of those items. Now, the un-selected cart items, although not visible in the cart, are still preserved in the DB and will be pulled if another condition is met.
I have come across the filter woocommerce_cart_item_visible
to 'hide' some cart items from the cart. It works as expected but just 'hides' the products while still adding their amount in the cart totals.
I could also try WC()->cart->remove_cart_item( $cart_item_key );
but it will remove the item from the DB too.
How can I achieve this?
CodePudding user response:
Here is something you can try :
add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_items_from_cart' );
function conditionally_remove_items_from_cart( $cart ) {
if ( ! is_admin() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// get the product id
$product_id = $cart_item['product_id'];
// get the quantity
$quantity = $cart_item['quantity'];
// get the subtotal
$subtotal = $cart_item['line_subtotal'];
// check your conditions here
if ( $condition1 && $condition2 ) {
$cart->remove_cart_item( $cart_item_key );
}
}
}
}