Commit 2da1309ea57 for woocommerce
commit 2da1309ea5779a711343602de7e78794045dbba2
Author: Albert Juhé Lluveras <contact@albertjuhe.com>
Date: Mon Nov 16 10:21:35 2026 +0100
Verify there aren't more specific variations when adding a variation to cart (#70776)
* Verify there aren't more specific variations when adding a variation to cart
* Add changelog file
* Mark changlog as a fix
* Only check if there is an earlier match, regardless of its specificity
* Check matching attributes before loading product objects
* Call get_available_variation() to make sure filters are applied
* Simplify attributes comparison
* Remove unnecessary return
* Linting
* Expand tests
* Revert "Remove unnecessary return"
This reverts commit 34bb466b655582ffa32c0ee0009979c2c5ed033a.
* Code cleanup
* Optimize _prime_post_caches()
* Normalize child IDs before searching
* Move complex tests into EarlierVariationMatch
* Rename EarlierVariationMatch to VariationMatcher
diff --git a/plugins/woocommerce/changelog/fix-WOO6-365-ii b/plugins/woocommerce/changelog/fix-WOO6-365-ii
new file mode 100644
index 00000000000..00459fa0116
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-WOO6-365-ii
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Stop a later variation from being added when an earlier variation already matches the selected options.
diff --git a/plugins/woocommerce/includes/class-wc-cart.php b/plugins/woocommerce/includes/class-wc-cart.php
index 8332d29a94e..e38a2d746eb 100644
--- a/plugins/woocommerce/includes/class-wc-cart.php
+++ b/plugins/woocommerce/includes/class-wc-cart.php
@@ -14,6 +14,7 @@ use Automattic\WooCommerce\Enums\ProductStatus;
use Automattic\WooCommerce\Enums\ProductType;
use Automattic\WooCommerce\Enums\TaxDisplayMode;
use Automattic\WooCommerce\Internal\ProductVariations\SelectedVariationName;
+use Automattic\WooCommerce\Internal\ProductVariations\VariationMatcher;
use Automattic\WooCommerce\Internal\Tax\TaxRateDataStore;
use Automattic\WooCommerce\StoreApi\Utilities\LocalPickupUtils;
use Automattic\WooCommerce\Utilities\DiscountsUtil;
@@ -1322,6 +1323,13 @@ class WC_Cart extends WC_Legacy_Cart {
/* translators: %s: Attribute name. */
throw new Exception( sprintf( _n( '%s is a required field', '%s are required fields', count( $missing_attributes ), 'woocommerce' ), wc_format_list_of_items( $missing_attributes ) ) );
}
+
+ if (
+ $product_data instanceof WC_Product_Variation &&
+ wc_get_container()->get( VariationMatcher::class )->has_earlier_match( $product_data, $variation )
+ ) {
+ throw new Exception( __( 'The selected options belong to a different variation of this product.', 'woocommerce' ) );
+ }
}
// Validate variation ID.
diff --git a/plugins/woocommerce/src/Internal/ProductVariations/VariationMatcher.php b/plugins/woocommerce/src/Internal/ProductVariations/VariationMatcher.php
new file mode 100644
index 00000000000..088d7871b2d
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/ProductVariations/VariationMatcher.php
@@ -0,0 +1,127 @@
+<?php
+/**
+ * Checks whether an earlier variation already matches an add to cart selection.
+ *
+ * @package WooCommerce\Internal\ProductVariations
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\ProductVariations;
+
+use WC_Product_Variable;
+use WC_Product_Variation;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Detects when an earlier variation already matches the attributes being added.
+ *
+ * @internal
+ *
+ * @since 11.4.0
+ */
+class VariationMatcher {
+
+ /**
+ * Whether an earlier available variation matches this selection.
+ *
+ * Fully specified variations return false, so they can still be added by their own ID. Disabled and unpriced variations are ignored, as are variations removed by woocommerce_available_variation. Out-of-stock variations are ignored when out-of-stock products are hidden from the catalog.
+ *
+ * @since 11.4.0
+ *
+ * @param WC_Product_Variation $variation Variation being added to the cart.
+ * @param array<string, mixed> $selected_attributes Selected add-to-cart attribute values.
+ * @return bool
+ */
+ public function has_earlier_match( WC_Product_Variation $variation, array $selected_attributes ): bool {
+ $current_any_count = count( array_keys( $variation->get_attributes( 'edit' ), '', true ) );
+ if ( 0 === $current_any_count ) {
+ return false;
+ }
+
+ $parent = wc_get_product( $variation->get_parent_id() );
+ if ( ! $parent instanceof WC_Product_Variable ) {
+ return false;
+ }
+
+ $child_ids = array_values( array_map( 'absint', $parent->get_children() ) );
+ $selected_index = array_search( $variation->get_id(), $child_ids, true );
+ if ( ! is_int( $selected_index ) || 0 === $selected_index ) {
+ return false;
+ }
+
+ $earlier_ids = array_slice( $child_ids, 0, $selected_index );
+ if ( ! empty( $earlier_ids ) ) {
+ _prime_post_caches( $earlier_ids );
+ }
+
+ foreach ( $earlier_ids as $child_id ) {
+ if ( ! $this->attributes_match( $child_id, $selected_attributes ) ) {
+ continue;
+ }
+
+ $earlier = wc_get_product( $child_id );
+ if ( $earlier instanceof WC_Product_Variation && $this->is_available( $earlier, $parent ) ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Whether the variation's stored attributes match the selection.
+ *
+ * Empty attribute values are "any" and match every selection.
+ *
+ * @param int $variation_id Variation ID.
+ * @param array<string, mixed> $selected Selected attribute values, keyed by attribute meta key.
+ * @return bool
+ */
+ private function attributes_match( int $variation_id, array $selected ): bool {
+ foreach ( wc_get_product_variation_attributes( $variation_id ) as $name => $value ) {
+ if ( '' === $value ) {
+ continue;
+ }
+
+ $selected_value = $selected[ $name ] ?? null;
+ if ( ! is_scalar( $selected_value ) || (string) $selected_value !== (string) $value ) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Whether the variation can be selected from the catalog.
+ *
+ * @param WC_Product_Variation $variation Variation to check.
+ * @param WC_Product_Variable $parent_product Parent variable product.
+ * @return bool
+ */
+ private function is_available( WC_Product_Variation $variation, WC_Product_Variable $parent_product ): bool {
+ if ( ! $variation->exists() ) {
+ return false;
+ }
+
+ $hide_out_of_stock = 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' );
+ if ( $hide_out_of_stock && ! $variation->is_in_stock() ) {
+ return false;
+ }
+
+ /**
+ * This filter is documented in includes/class-wc-product-variable.php.
+ *
+ * @since 2.6.8
+ */
+ $hide_invisible = apply_filters( 'woocommerce_hide_invisible_variations', true, $parent_product->get_id(), $variation );
+
+ if ( $hide_invisible && ! $variation->variation_is_visible() ) {
+ return false;
+ }
+
+ return (bool) $parent_product->get_available_variation( $variation );
+ }
+}
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/CartController.php b/plugins/woocommerce/src/StoreApi/Utilities/CartController.php
index 3a80f89eb34..dc4308fae37 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/CartController.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/CartController.php
@@ -4,6 +4,7 @@ namespace Automattic\WooCommerce\StoreApi\Utilities;
use Automattic\WooCommerce\Checkout\Helpers\ReserveStock;
use Automattic\WooCommerce\Enums\ProductStatus;
use Automattic\WooCommerce\Enums\ProductType;
+use Automattic\WooCommerce\Internal\ProductVariations\VariationMatcher;
use Automattic\WooCommerce\StoreApi\Exceptions\InvalidCartException;
use Automattic\WooCommerce\StoreApi\Exceptions\NotPurchasableException;
use Automattic\WooCommerce\StoreApi\Exceptions\OutOfStockException;
@@ -1370,6 +1371,18 @@ class CartController {
);
}
+ $variation_product = wc_get_product( $request['id'] );
+ if (
+ $variation_product instanceof \WC_Product_Variation &&
+ wc_get_container()->get( VariationMatcher::class )->has_earlier_match( $variation_product, $request['variation'] )
+ ) {
+ throw new RouteException(
+ 'woocommerce_rest_invalid_variation_data',
+ esc_html__( 'The selected options belong to a different variation of this product.', 'woocommerce' ),
+ 400
+ );
+ }
+
ksort( $request['variation'] );
return $request;
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-cart-test.php b/plugins/woocommerce/tests/php/includes/class-wc-cart-test.php
index 7381d3d705d..9429152a211 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-cart-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-cart-test.php
@@ -853,6 +853,7 @@ class WC_Cart_Test extends \WC_Unit_Test_Case {
$fixed_variation->set_parent_id( $product->get_id() );
$fixed_variation->set_attributes( array( 'finish' => 'Black%20White' ) );
$fixed_variation->set_regular_price( '10' );
+ $fixed_variation->set_menu_order( 1 );
$fixed_variation->save();
$cart_item_key = WC()->cart->add_to_cart( $product->get_id(), 1, $fixed_variation->get_id(), array( 'attribute_finish' => 'Black%20White' ) );
@@ -862,10 +863,12 @@ class WC_Cart_Test extends \WC_Unit_Test_Case {
WC()->cart->empty_cart();
+ // Ordered before the fixed variation so that variation does not claim this selection.
$any_variation = new WC_Product_Variation();
$any_variation->set_parent_id( $product->get_id() );
$any_variation->set_attributes( array( 'finish' => '' ) );
$any_variation->set_regular_price( '10' );
+ $any_variation->set_menu_order( 0 );
$any_variation->save();
$any_cart_item_key = WC()->cart->add_to_cart( $product->get_id(), 1, $any_variation->get_id(), array( 'attribute_finish' => 'Black%20White' ) );
@@ -3032,4 +3035,44 @@ class WC_Cart_Test extends \WC_Unit_Test_Case {
$first_child->delete( true );
}
}
+
+ /**
+ * @testdox Add to cart rejects a variation when an earlier variation matches.
+ */
+ public function test_add_to_cart_rejects_a_variation_when_an_earlier_variation_matches(): void {
+ $product = new WC_Product_Variable();
+ $attribute = new WC_Product_Attribute();
+ $attribute->set_name( 'Color' );
+ $attribute->set_options( array( 'Red' ) );
+ $attribute->set_variation( true );
+ $product->set_attributes( array( $attribute ) );
+ $product->save();
+
+ $red = new WC_Product_Variation();
+ $red->set_parent_id( $product->get_id() );
+ $red->set_attributes( array( 'color' => 'Red' ) );
+ $red->set_regular_price( '10' );
+ $red->set_menu_order( 0 );
+ $red->save();
+
+ $any = new WC_Product_Variation();
+ $any->set_parent_id( $product->get_id() );
+ $any->set_attributes( array( 'color' => '' ) );
+ $any->set_regular_price( '5' );
+ $any->set_menu_order( 1 );
+ $any->save();
+
+ wc_clear_notices();
+ $cart_item_key = WC()->cart->add_to_cart(
+ $product->get_id(),
+ 1,
+ $any->get_id(),
+ array(
+ 'attribute_color' => 'Red',
+ )
+ );
+
+ $this->assertFalse( $cart_item_key, 'Add to cart should reject a variation when an earlier variation matches.' );
+ $this->assertSame( 'The selected options belong to a different variation of this product.', wc_get_notices( 'error' )[0]['notice'] );
+ }
}
diff --git a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartControllerTests.php b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartControllerTests.php
index ebf01549546..3d23b45ae1a 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartControllerTests.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/StoreApi/Utilities/CartControllerTests.php
@@ -3,10 +3,10 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Blocks\StoreApi\Utilities;
+use Automattic\WooCommerce\Enums\ProductStockStatus;
use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
use Automattic\WooCommerce\StoreApi\Utilities\CartController;
use Automattic\WooCommerce\Tests\Blocks\Helpers\FixtureData;
-use Automattic\WooCommerce\Enums\ProductStockStatus;
/**
* Unit tests for the CartController class.
@@ -434,4 +434,50 @@ class CartControllerTests extends \WC_Unit_Test_Case {
$this->assertStringContainsString( 'Invalid value posted for Color', $exception->getMessage() );
}
}
+
+ /**
+ * @testdox Add to cart rejects a variation when an earlier variation matches.
+ */
+ public function test_add_to_cart_rejects_a_variation_when_an_earlier_variation_matches(): void {
+ $product = new \WC_Product_Variable();
+ $attribute = new \WC_Product_Attribute();
+ $attribute->set_name( 'Color' );
+ $attribute->set_options( array( 'Red' ) );
+ $attribute->set_variation( true );
+ $product->set_attributes( array( $attribute ) );
+ $product->save();
+
+ $red = new \WC_Product_Variation();
+ $red->set_parent_id( $product->get_id() );
+ $red->set_attributes( array( 'color' => 'Red' ) );
+ $red->set_regular_price( '10' );
+ $red->set_menu_order( 0 );
+ $red->save();
+
+ $any = new \WC_Product_Variation();
+ $any->set_parent_id( $product->get_id() );
+ $any->set_attributes( array( 'color' => '' ) );
+ $any->set_regular_price( '5' );
+ $any->set_menu_order( 1 );
+ $any->save();
+
+ try {
+ ( new CartController() )->add_to_cart(
+ array(
+ 'id' => $any->get_id(),
+ 'quantity' => 1,
+ 'variation' => array(
+ array(
+ 'attribute' => 'Color',
+ 'value' => 'Red',
+ ),
+ ),
+ )
+ );
+ $this->fail( 'Add to cart should reject a variation when an earlier variation matches.' );
+ } catch ( RouteException $exception ) {
+ $this->assertSame( 'woocommerce_rest_invalid_variation_data', $exception->getErrorCode() );
+ $this->assertSame( 'The selected options belong to a different variation of this product.', $exception->getMessage() );
+ }
+ }
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/ProductVariations/VariationMatcherTest.php b/plugins/woocommerce/tests/php/src/Internal/ProductVariations/VariationMatcherTest.php
new file mode 100644
index 00000000000..3b3f2c271ac
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/ProductVariations/VariationMatcherTest.php
@@ -0,0 +1,294 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\ProductVariations;
+
+use Automattic\WooCommerce\Enums\ProductStockStatus;
+use Automattic\WooCommerce\Internal\ProductVariations\VariationMatcher;
+use WC_Product_Attribute;
+use WC_Product_Variable;
+use WC_Product_Variation;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for VariationMatcher.
+ */
+class VariationMatcherTest extends WC_Unit_Test_Case {
+
+ /**
+ * The System Under Test.
+ *
+ * @var VariationMatcher
+ */
+ private $sut;
+
+ /**
+ * Set up test fixtures.
+ */
+ public function setUp(): void {
+ parent::setUp();
+
+ $this->sut = new VariationMatcher();
+ }
+
+ /**
+ * @testdox has_earlier_match follows menu order and ignores unavailable earlier variations.
+ *
+ * @dataProvider provide_menu_order_cases
+ *
+ * @param string $variation_key Variation being checked.
+ * @param array<string, string> $selected Selected attribute values.
+ * @param bool $expected Whether an earlier variation matches.
+ * @param string $message Assertion message.
+ */
+ public function test_has_earlier_match_follows_menu_order( string $variation_key, array $selected, bool $expected, string $message ): void {
+ $variations = $this->create_color_and_size_variations();
+
+ $this->assertSame( $expected, $this->sut->has_earlier_match( $variations[ $variation_key ], $selected ), $message );
+ }
+
+ /**
+ * Menu order and availability cases.
+ *
+ * Variations, in menu order: Red/Any size, unpriced Blue/Large, Red/Large, Any color/Small, Any/Any.
+ *
+ * @return array<string, array{0: string, 1: array<string, string>, 2: bool, 3: string}>
+ */
+ public function provide_menu_order_cases(): array {
+ $red_large = array(
+ 'attribute_color' => 'Red',
+ 'attribute_size' => 'Large',
+ );
+
+ return array(
+ 'fully specified variation' => array(
+ 'red_large',
+ $red_large,
+ false,
+ 'A fully specified variation should not match an earlier variation.',
+ ),
+ 'unpriced earlier variation' => array(
+ 'any',
+ array(
+ 'attribute_color' => 'Blue',
+ 'attribute_size' => 'Large',
+ ),
+ false,
+ 'An unpriced earlier variation should be ignored.',
+ ),
+ 'variation ordered first' => array(
+ 'red_any_size',
+ $red_large,
+ false,
+ 'A variation ordered before a closer match should not report an earlier match.',
+ ),
+ 'later any variation' => array(
+ 'any',
+ $red_large,
+ true,
+ 'A later Any variation should match an earlier available variation.',
+ ),
+ 'no earlier variation matches' => array(
+ 'any_color_small',
+ array(
+ 'attribute_color' => 'Blue',
+ 'attribute_size' => 'Small',
+ ),
+ false,
+ 'A variation should be allowed when no earlier variation matches.',
+ ),
+ 'same number of Any attributes' => array(
+ 'any_color_small',
+ array(
+ 'attribute_color' => 'Red',
+ 'attribute_size' => 'Small',
+ ),
+ true,
+ 'A later variation should match an earlier one with the same number of Any attributes.',
+ ),
+ );
+ }
+
+ /**
+ * @testdox An out-of-stock earlier variation is ignored when out-of-stock products are hidden.
+ */
+ public function test_ignores_out_of_stock_earlier_variation_when_hidden_from_catalog(): void {
+ update_option( 'woocommerce_hide_out_of_stock_items', 'yes' );
+
+ $product = $this->create_variable_product(
+ array(
+ array(
+ 'name' => 'Color',
+ 'options' => array( 'Red', 'Blue' ),
+ ),
+ )
+ );
+ $red = $this->create_variation( $product, array( 'color' => 'Red' ), '10', 0 );
+ $red->set_stock_status( ProductStockStatus::OUT_OF_STOCK );
+ $red->save();
+ $any = $this->create_variation( $product, array( 'color' => '' ), '5', 1 );
+
+ $this->assertFalse(
+ $this->sut->has_earlier_match(
+ $any,
+ array(
+ 'attribute_color' => 'Red',
+ )
+ ),
+ 'An out-of-stock earlier variation should be ignored when hidden from the catalog.'
+ );
+ }
+
+ /**
+ * @testdox An earlier variation hidden by woocommerce_available_variation is ignored.
+ */
+ public function test_ignores_earlier_variation_hidden_by_available_variation_filter(): void {
+ $product = $this->create_variable_product(
+ array(
+ array(
+ 'name' => 'Color',
+ 'options' => array( 'Blue' ),
+ ),
+ )
+ );
+ $blue = $this->create_variation( $product, array( 'color' => 'Blue' ), '50', 0 );
+ $any = $this->create_variation( $product, array( 'color' => '' ), '40', 1 );
+
+ add_filter(
+ 'woocommerce_available_variation',
+ static function ( $data, $variable_product, $variation ) use ( $blue ) {
+ unset( $variable_product );
+ if ( $variation instanceof WC_Product_Variation && $blue->get_id() === $variation->get_id() ) {
+ return false;
+ }
+ return $data;
+ },
+ 10,
+ 3
+ );
+
+ $this->assertFalse(
+ $this->sut->has_earlier_match(
+ $any,
+ array(
+ 'attribute_color' => 'Blue',
+ )
+ ),
+ 'An earlier variation hidden by woocommerce_available_variation should be ignored.'
+ );
+ }
+
+ /**
+ * Create the color and size variations used by the menu-order cases.
+ *
+ * @return array<string, WC_Product_Variation>
+ */
+ private function create_color_and_size_variations(): array {
+ $product = $this->create_variable_product(
+ array(
+ array(
+ 'name' => 'Color',
+ 'options' => array( 'Red', 'Blue' ),
+ ),
+ array(
+ 'name' => 'Size',
+ 'options' => array( 'Large', 'Small' ),
+ ),
+ )
+ );
+
+ return array(
+ 'red_any_size' => $this->create_variation(
+ $product,
+ array(
+ 'color' => 'Red',
+ 'size' => '',
+ ),
+ '5',
+ 0
+ ),
+ 'blue_large' => $this->create_variation(
+ $product,
+ array(
+ 'color' => 'Blue',
+ 'size' => 'Large',
+ ),
+ '',
+ 1
+ ),
+ 'red_large' => $this->create_variation(
+ $product,
+ array(
+ 'color' => 'Red',
+ 'size' => 'Large',
+ ),
+ '8',
+ 2
+ ),
+ 'any_color_small' => $this->create_variation(
+ $product,
+ array(
+ 'color' => '',
+ 'size' => 'Small',
+ ),
+ '6',
+ 3
+ ),
+ 'any' => $this->create_variation(
+ $product,
+ array(
+ 'color' => '',
+ 'size' => '',
+ ),
+ '10',
+ 4
+ ),
+ );
+ }
+
+ /**
+ * Create a variable product.
+ *
+ * @param array<int, array{name: string, options: array<int, string>}> $attributes Attribute name and options.
+ * @return WC_Product_Variable
+ */
+ private function create_variable_product( array $attributes ): WC_Product_Variable {
+ $product = new WC_Product_Variable();
+ $product_attributes = array();
+
+ foreach ( $attributes as $attribute ) {
+ $product_attribute = new WC_Product_Attribute();
+ $product_attribute->set_name( $attribute['name'] );
+ $product_attribute->set_options( $attribute['options'] );
+ $product_attribute->set_variation( true );
+ $product_attributes[] = $product_attribute;
+ }
+
+ $product->set_attributes( $product_attributes );
+ $product->save();
+
+ return $product;
+ }
+
+ /**
+ * Create a variation. An empty attribute value is Any, and an empty price leaves it unpriced.
+ *
+ * @param WC_Product_Variable $parent_product Parent product.
+ * @param array<string, string> $attributes Variation attributes.
+ * @param string $price Regular price.
+ * @param int $menu_order Menu order.
+ * @return WC_Product_Variation
+ */
+ private function create_variation( WC_Product_Variable $parent_product, array $attributes, string $price, int $menu_order ): WC_Product_Variation {
+ $variation = new WC_Product_Variation();
+ $variation->set_parent_id( $parent_product->get_id() );
+ $variation->set_attributes( $attributes );
+ if ( '' !== $price ) {
+ $variation->set_regular_price( $price );
+ }
+ $variation->set_menu_order( $menu_order );
+ $variation->save();
+
+ return $variation;
+ }
+}