php - Only keep in cart the last variation from WooCommerce variable products

one text

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.

Source