Search code examples
phpwordpresswoocommercehook-woocommerce

Woocommerce. if product is not in cart, remove additional product from cart. not working


i want to do something like this, in woocommerce. If specific product ids are only items in cart i want cart to be emptied, here is my code:

add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_a_discounted_product' );
function conditionally_remove_a_discounted_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

// Settings
$discounted_product_id = array('2877','2876','2874','2873','2871','2833','2831','2832','2525','2524');

// Initializing variables
$discounted_item_key = false;

// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
    // When free productis is cart
    if ( in_array( $discounted_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
        $discounted_item_key = $cart_item_key;
    }
    // if any other product is in cart: EXIT
    else {
       return;
    }  
}
// When the discounted product is alone in cart, remove it
if( $discounted_item_key ) {
    // display notice on removal (optional)
    wc_clear_notices();
    wc_add_notice( __("Cart Emptied"), 'notice' );

    WC()->cart->empty_cart();
}}

but it's not working can i know why? its not emptying cart, if only products which are in array are only items in cart.


Solution

  • I revised your code.

    add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_a_discounted_product' );
    function conditionally_remove_a_discounted_product( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Settings
        $discounted_product_id = array('2877','2876','2874','2873','2871','2833','2831','2832','2525','2524');
    
        // Initializing variables
        $discounted_item_key = false;
    
        // Loop through cart items (first loop)
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
            // When free productis is cart
            if ( in_array( $cart_item['product_id'], $discounted_product_id ) || in_array( $cart_item['variation_id'], $discounted_product_id ) ) {
                $discounted_item_key = $cart_item_key;
            }
            // if any other product is in cart: EXIT
            else {
               return;
            }  
        }
        // When the discounted product is alone in cart, remove it
        if( $discounted_item_key ) {
            // display notice on removal (optional)
            wc_clear_notices();
            wc_add_notice( __("Cart Emptied"), 'notice' );
    
            WC()->cart->empty_cart();
        }
    }