Ad

Issue Allow Only One Product In WooCommerce Cart

We have a booking system which should allow only one product in the cart (when customers adds next product, previous one should be deleted from the cart).

Until today we have been using following code:

add_filter( 'woocommerce_add_to_cart_validation', 'b_only_one_in_cart', 99, 2 );
   
function b_only_one_in_cart( $passed, $added_product_id ) {
   wc_empty_cart();
   return $passed;
}

But it ceased to work (and I can't find why). Has something changed in the recent version of WooCommerce? How can I get it to work again?

Ad

Answer

You could use WC()->cart->empty_cart(); instead

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // When NOT empty
    if ( ! WC()->cart->is_empty() ) {
        // Empties the cart and optionally the persistent cart too.
        WC()->cart->empty_cart();
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );

If the above does not work for some reason, you can also apply it in the following way: (Solution for PHP 7.3 and up)

// Used to calculate totals
function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;
    
    // Get cart
    $get_cart = $cart->get_cart();

    // Solution for PHP 7.3 and up
    foreach ( $get_cart as $cart_item_key => $cart_item ) {
        // NOT last element
        if ( $cart_item_key !== array_key_last( $get_cart ) ) {
            // Remove a cart item
            $cart->remove_cart_item( $cart_item_key );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
Ad
source: stackoverflow.com
Ad