How to remove an item from cart based on condition in woocommerce?

Member

by dana , in category: PHP CMS , 14 days ago

How to remove an item from cart based on condition in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 14 days ago

@dana 

To remove an item from the cart in WooCommerce based on a specific condition, you can use the woocommerce_before_cart_item_quantity_zero hook. Here's an example of how you can achieve this:

  1. Open your theme's functions.php file.
  2. Add the following code snippet to the file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
add_action( 'woocommerce_before_cart_item_quantity_zero', 'custom_remove_cart_item', 10, 1 );

function custom_remove_cart_item( $cart_item_key ) {
    // Get the cart contents
    $cart = WC()->cart->get_cart();

    // Loop through each item in the cart
    foreach ( $cart as $key => $item ) {
        // Check if the item meets your condition
        if ( $cart_item_key === $key ) {
            // Remove the item from the cart
            WC()->cart->remove_cart_item( $key );
            break;
        }
    }
}


  1. Replace custom_remove_cart_item with the name of your custom function and add your specific condition inside the if statement.
  2. Save the changes to the functions.php file.


Now, when the quantity of a cart item is set to zero, it will be removed from the cart based on the condition you specified in the custom function.