Search code examples
phpwordpresswoocommercecartproduct-variations

Only keep in cart the last variation from WooCommerce variable products


I have 1 Product with 3 Variations and I only want 1 variation in the cart at a time from the same variable product, but don't want to create a roadblock with an error message and a dead-end.

I want to swap the variations if the same product is added.

So if a customer adds Product 1 Variation 1 to cart and then they go back and add the same product but a different variation (Product 1 Variation 2), I want the function to remove Variation 1 and add Variation 2.

Here's what I've come up with so far -- I've tested and it works, but idk if there's an easier way or if I might break something else

add_action( 'woocommerce_add_to_cart', 'check_product_added_to_cart', 10, 6 );
function check_product_added_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {

    // First Variation
    $product_a = 5831;
    // Second Variation
    $product_b = 5830;
    // Third Variation
    $product_c = 5832;

    // Initialising some variables
    $has_item = false;
    $is_product_id = false;

    foreach( WC()->cart->get_cart() as $key => $item ){
        // Check if the item to remove is in cart
        if( $item['product_id'] == $product_b || $product_c ){
            $has_item = true;
            $key_to_remove = $key;
        }

        // Check if we add to cart the targeted product ID
        if( $product_id == $product_a ){
            $is_product_id = true;
        }
    }

    if( $has_item && $is_product_id ){
        WC()->cart->remove_cart_item($key_to_remove);
    }
}

Solution

  • The following will only keep "silently" in cart the last variation from a variable product:

    add_action('woocommerce_before_calculate_totals', 'keep_last_variation_from_variable_products', 10, 1 );
    function keep_last_variation_from_variable_products( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $parent_ids = array();
    
        foreach (  $cart->get_cart() as $cart_item_key => $cart_item ) {
            // Only for product variations
            if ( $cart_item['variation_id'] > 0 ) {
                // When a variable product exist already in cart
                if( isset($parent_ids[$cart_item['product_id']]) && ! empty($parent_ids[$cart_item['product_id']]) ) {
                    // Remove it
                    $cart->remove_cart_item($parent_ids[$cart_item['product_id']]);
                }
                // Set in the array the cart item key for variable product id key
                $parent_ids[$cart_item['product_id']] = $cart_item_key;
            }
        }
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.