Commit b4a79b3bcf5 for woocommerce

commit b4a79b3bcf54742134ccacc120c0554bb2a3a279
Author: Ahmed Ismail <105542236+ahmedevsaad@users.noreply.github.com>
Date:   Thu Nov 26 15:59:56 2026 +0200

    Allow setting product and variation attribute terms by ID in the REST API (#69768)

    * Allow setting attribute terms by ID in the products REST API

    Product attributes accept term_ids and variation attributes accept
    term_id, so terms that share a name can be targeted exactly.

    * Reject attribute term IDs that don't belong to the attribute

    * Look up attribute term IDs in the attribute's own taxonomy name

    Pass wc_attribute_taxonomy_name_by_id() to get_term() directly, so the
    taxonomy is always a string (PHPStan flagged the array|string type).

    * Reject zero and negative attribute term IDs

    A posted term_id of 0 no longer falls back to the name lookup and saves "Any", and absint() no longer turns -42 into term 42. The schemas now declare a minimum of 1; the controller check covers batch requests, which skip schema validation.

    * Reject fractional attribute term IDs in REST batch requests

    * Validate attribute term fields before variation image writes

    * Fix malformed REST product attribute entries

    * Reject array options in variation REST requests

    * Fix variation REST attribute taxonomy sanitization

    ---------

    Co-authored-by: Tom Cafferkey <tjcafferkey@gmail.com>

diff --git a/plugins/woocommerce/changelog/fix-35615-rest-attribute-term-id-slug b/plugins/woocommerce/changelog/fix-35615-rest-attribute-term-id-slug
new file mode 100644
index 00000000000..70d4c996c75
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-35615-rest-attribute-term-id-slug
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+REST API: set product and variation attribute terms by ID, so terms that share a name are no longer mixed up.
diff --git a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller.php b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller.php
index d82c43ff57c..f36c01ed3f1 100644
--- a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller.php
+++ b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller.php
@@ -206,7 +206,8 @@ class WC_REST_Product_Variations_Controller extends WC_REST_Product_Variations_V
 	 * @param  WP_REST_Request $request Request object.
 	 * @param  bool            $creating If is creating a new object.
 	 * @return WP_Error|WC_Data
-	 * @throws \Throwable When setting gallery_image_ids fails.
+	 * @throws \Throwable When setting gallery images fails or an attribute term ID is invalid.
+	 * @throws WC_REST_Exception When an attribute option is an array.
 	 */
 	protected function prepare_object_for_database( $request, $creating = false ) {
 		$customs = CustomsDataValidator::normalize_fields( $request->get_params() );
@@ -221,6 +222,22 @@ class WC_REST_Product_Variations_Controller extends WC_REST_Product_Variations_V
 		}

 		$variation->set_parent_id( absint( $request['product_id'] ) );
+		$attribute_terms = array();
+		if ( isset( $request['attributes'] ) ) {
+			foreach ( $request['attributes'] as $index => $attribute ) {
+				if ( ! is_array( $attribute ) ) {
+					continue;
+				}
+				if ( isset( $attribute['option'] ) && is_array( $attribute['option'] ) ) {
+					throw new WC_REST_Exception( 'woocommerce_rest_invalid_attribute_option', esc_html__( 'Attribute option must be a single value, not an array.', 'woocommerce' ), 400 );
+				}
+				if ( ! array_key_exists( 'term_id', $attribute ) ) {
+					continue;
+				}
+				$taxonomy                  = ! empty( $attribute['id'] ) ? wc_attribute_taxonomy_name_by_id( absint( $attribute['id'] ) ) : wc_sanitize_taxonomy_name( is_string( $attribute['name'] ?? null ) ? $attribute['name'] : '' );
+				$attribute_terms[ $index ] = $this->get_attribute_term( $attribute['term_id'], $taxonomy );
+			}
+		}

 		foreach ( $customs as $property => $value ) {
 			$variation->{ 'set_' . $property }( $value );
@@ -404,7 +421,11 @@ class WC_REST_Product_Variations_Controller extends WC_REST_Product_Variations_V

 			$parent_attributes = $parent->get_attributes();

-			foreach ( $request['attributes'] as $attribute ) {
+			foreach ( $request['attributes'] as $index => $attribute ) {
+				if ( ! is_array( $attribute ) ) {
+					continue;
+				}
+
 				$attribute_id   = 0;
 				$attribute_name = '';

@@ -428,8 +449,12 @@ class WC_REST_Product_Variations_Controller extends WC_REST_Product_Variations_V
 				$attribute_value = isset( $attribute['option'] ) ? wc_clean( rawurldecode( stripslashes( $attribute['option'] ) ) ) : '';

 				if ( $parent_attributes[ $attribute_name ]->is_taxonomy() ) {
-					// If dealing with a taxonomy, we need to get the slug from the name posted to the API.
-					$term = get_term_by( 'name', $attribute_value, $parent_attributes[ $attribute_name ]->get_name() );
+					// A term ID identifies the term exactly; otherwise get the slug from the name posted to the API.
+					if ( isset( $attribute_terms[ $index ] ) ) {
+						$term = $attribute_terms[ $index ];
+					} else {
+						$term = get_term_by( 'name', $attribute_value, $parent_attributes[ $attribute_name ]->get_name() );
+					}

 					if ( $term && ! is_wp_error( $term ) ) {
 						$attribute_value = $term->slug;
@@ -470,6 +495,24 @@ class WC_REST_Product_Variations_Controller extends WC_REST_Product_Variations_V
 		return apply_filters( "woocommerce_rest_pre_insert_{$this->post_type}_object", $variation, $request, $creating );
 	}

+	/**
+	 * Get a global attribute term before processing variation images.
+	 *
+	 * @param mixed $posted_term_id Requested term ID.
+	 * @param mixed $taxonomy       Global attribute taxonomy.
+	 * @return WP_Term
+	 * @throws WC_REST_Exception When the term ID or taxonomy is invalid.
+	 */
+	private function get_attribute_term( $posted_term_id, $taxonomy ): WP_Term {
+		$term_id = is_numeric( $posted_term_id ) && (float) (int) $posted_term_id === (float) $posted_term_id ? (int) $posted_term_id : 0;
+		$term    = $term_id > 0 && is_string( $taxonomy ) && taxonomy_exists( $taxonomy ) && taxonomy_is_product_attribute( $taxonomy ) ? get_term_by( 'id', $term_id, $taxonomy ) : false;
+		if ( ! $term instanceof WP_Term ) {
+			/* translators: %d: term ID */
+			throw new WC_REST_Exception( 'woocommerce_rest_invalid_attribute_term_id', esc_html( sprintf( __( '#%d is not a term of this attribute.', 'woocommerce' ), $term_id ) ), 400 );
+		}
+		return $term;
+	}
+
 	/**
 	 * Get the image for a product variation.
 	 *
@@ -912,21 +955,27 @@ class WC_REST_Product_Variations_Controller extends WC_REST_Product_Variations_V
 					'items'       => array(
 						'type'       => 'object',
 						'properties' => array(
-							'id'     => array(
+							'id'      => array(
 								'description' => __( 'Attribute ID.', 'woocommerce' ),
 								'type'        => 'integer',
 								'context'     => array( 'view', 'edit' ),
 							),
-							'name'   => array(
+							'name'    => array(
 								'description' => __( 'Attribute name.', 'woocommerce' ),
 								'type'        => 'string',
 								'context'     => array( 'view', 'edit' ),
 							),
-							'option' => array(
+							'option'  => array(
 								'description' => __( 'Selected attribute term name.', 'woocommerce' ),
 								'type'        => 'string',
 								'context'     => array( 'view', 'edit' ),
 							),
+							'term_id' => array(
+								'description' => __( 'Selected term ID of a global attribute. When set, it is used instead of option.', 'woocommerce' ),
+								'type'        => 'integer',
+								'minimum'     => 1,
+								'context'     => array( 'edit' ),
+							),
 						),
 					),
 				),
diff --git a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller.php b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller.php
index 6ff6142eb1f..85ed07a82c1 100644
--- a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller.php
+++ b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller.php
@@ -803,6 +803,7 @@ class WC_REST_Products_Controller extends WC_REST_Products_V2_Controller {
 	 * @param  WP_REST_Request $request Request object.
 	 * @param  bool            $creating If is creating a new object.
 	 * @return WP_Error|WC_Data
+	 * @throws WC_REST_Exception When a product attribute or term ID is invalid.
 	 */
 	protected function prepare_object_for_database( $request, $creating = false ) {
 		$customs = CustomsDataValidator::normalize_fields( $request->get_params() );
@@ -909,24 +910,49 @@ class WC_REST_Products_Controller extends WC_REST_Products_V2_Controller {
 			$attributes = array();

 			foreach ( $request['attributes'] as $attribute ) {
+				if ( ! is_array( $attribute ) ) {
+					throw new WC_REST_Exception( 'woocommerce_rest_invalid_attribute', esc_html__( 'Each attribute must be an object.', 'woocommerce' ), 400 );
+				}
+
 				$attribute_id   = 0;
 				$attribute_name = '';

 				// Check ID for global attributes or name for product attributes.
 				if ( ! empty( $attribute['id'] ) ) {
-					$attribute_id   = absint( $attribute['id'] );
-					$attribute_name = wc_attribute_taxonomy_name_by_id( $attribute_id );
+					$attribute_id = absint( $attribute['id'] );
 				} elseif ( ! empty( $attribute['name'] ) ) {
 					$attribute_name = wc_clean( $attribute['name'] );
 				}

+				if ( array_key_exists( 'term_ids', $attribute ) && ( ! $attribute_id || ! is_array( $attribute['term_ids'] ) ) ) {
+					throw new WC_REST_Exception( 'woocommerce_rest_invalid_attribute_term_id', esc_html__( 'Term IDs must be an array belonging to a valid global attribute.', 'woocommerce' ), 400 );
+				}
+
 				if ( ! $attribute_id && ! $attribute_name ) {
 					continue;
 				}

 				if ( $attribute_id ) {
+					$attribute_name = wc_attribute_taxonomy_name_by_id( $attribute_id );
+
+					if ( array_key_exists( 'term_ids', $attribute ) ) {
+						if ( ! $attribute_name || ! taxonomy_exists( $attribute_name ) ) {
+							throw new WC_REST_Exception( 'woocommerce_rest_invalid_attribute_term_id', esc_html__( 'Term IDs must be an array belonging to a valid global attribute.', 'woocommerce' ), 400 );
+						}

-					if ( isset( $attribute['options'] ) ) {
+						// Term IDs identify terms exactly, even when several terms share a name.
+						$values = array();
+						foreach ( $attribute['term_ids'] as $posted_term_id ) {
+							// Batch requests skip schema validation, so reject non-integer IDs before converting them.
+							$term_id = is_numeric( $posted_term_id ) && (float) (int) $posted_term_id === (float) $posted_term_id ? (int) $posted_term_id : 0;
+							$term    = $term_id > 0 ? get_term( $term_id, wc_attribute_taxonomy_name_by_id( $attribute_id ) ) : null;
+							if ( ! $term instanceof WP_Term ) {
+								/* translators: %d: term ID */
+								throw new WC_REST_Exception( 'woocommerce_rest_invalid_attribute_term_id', esc_html( sprintf( __( '#%d is not a term of this attribute.', 'woocommerce' ), $term_id ) ), 400 );
+							}
+							$values[] = $term_id;
+						}
+					} elseif ( isset( $attribute['options'] ) ) {
 						$options = $attribute['options'];

 						if ( ! is_array( $attribute['options'] ) ) {
@@ -1820,6 +1846,15 @@ class WC_REST_Products_Controller extends WC_REST_Products_V2_Controller {
 								),
 								'context'     => array( 'view', 'edit' ),
 							),
+							'term_ids'  => array(
+								'description' => __( 'List of term IDs of a global attribute. When set, it is used instead of options.', 'woocommerce' ),
+								'type'        => 'array',
+								'items'       => array(
+									'type'    => 'integer',
+									'minimum' => 1,
+								),
+								'context'     => array( 'edit' ),
+							),
 						),
 					),
 				),
diff --git a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller-tests.php b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller-tests.php
index d836a765e85..d74f15edb70 100644
--- a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller-tests.php
+++ b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-variations-controller-tests.php
@@ -1564,4 +1564,292 @@ class WC_REST_Product_Variations_Controller_Tests extends WC_Unit_Test_Case {
 		$product->save();
 		return $product;
 	}
+
+	/**
+	 * @testdox A variation attribute can be set by term ID, so terms that share a name are not mixed up.
+	 */
+	public function test_create_variation_with_attribute_term_id(): void {
+		list( $attribute, $first_term_id, $second_term_id ) = $this->create_attribute_with_duplicate_term_names();
+
+		$product_attribute = new WC_Product_Attribute();
+		$product_attribute->set_id( $attribute['attribute_id'] );
+		$product_attribute->set_name( $attribute['attribute_taxonomy'] );
+		$product_attribute->set_options( array( $first_term_id, $second_term_id ) );
+		$product_attribute->set_variation( true );
+
+		$product = new WC_Product_Variable();
+		$product->set_attributes( array( $product_attribute ) );
+		$product->save();
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/' . $product->get_id() . '/variations' );
+		$request->set_body_params(
+			array(
+				'attributes' => array(
+					array(
+						'id'      => $attribute['attribute_id'],
+						'option'  => 'Green',
+						'term_id' => $second_term_id,
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 201, $response->get_status() );
+		$variation = wc_get_product( $response->get_data()['id'] );
+		$this->assertSame( 'trousers-green', $variation->get_attributes()[ $attribute['attribute_taxonomy'] ] );
+	}
+
+	/**
+	 * @testdox An unknown variation attribute term ID is rejected instead of saving "Any".
+	 */
+	public function test_create_variation_with_unknown_attribute_term_id_fails(): void {
+		list( $attribute, $first_term_id ) = $this->create_attribute_with_duplicate_term_names();
+
+		$product_attribute = new WC_Product_Attribute();
+		$product_attribute->set_id( $attribute['attribute_id'] );
+		$product_attribute->set_name( $attribute['attribute_taxonomy'] );
+		$product_attribute->set_options( array( $first_term_id ) );
+		$product_attribute->set_variation( true );
+
+		$product = new WC_Product_Variable();
+		$product->set_attributes( array( $product_attribute ) );
+		$product->save();
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/' . $product->get_id() . '/variations' );
+		$request->set_body_params(
+			array(
+				'attributes' => array(
+					array(
+						'id'      => $attribute['attribute_id'],
+						'term_id' => PHP_INT_MAX,
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 400, $response->get_status() );
+		$this->assertSame( 'woocommerce_rest_invalid_attribute_term_id', $response->get_data()['code'] );
+	}
+
+	/**
+	 * @testdox An invalid variation attribute term ID is rejected and keeps the saved selection.
+	 * @testWith [0]
+	 *           [-1]
+	 *           [1, 0.5]
+	 *
+	 * @param int   $sign   Multiplier applied to a real term ID: 0 posts 0, -1 posts the negated ID.
+	 * @param float $offset Fraction added to the term ID.
+	 */
+	public function test_batch_update_variation_rejects_non_positive_attribute_term_id( int $sign, float $offset = 0 ): void {
+		list( $attribute, $first_term_id, $second_term_id ) = $this->create_attribute_with_duplicate_term_names();
+		$taxonomy = $attribute['attribute_taxonomy'];
+
+		$product_attribute = new WC_Product_Attribute();
+		$product_attribute->set_id( $attribute['attribute_id'] );
+		$product_attribute->set_name( $taxonomy );
+		$product_attribute->set_options( array( $first_term_id, $second_term_id ) );
+		$product_attribute->set_variation( true );
+
+		$product = new WC_Product_Variable();
+		$product->set_attributes( array( $product_attribute ) );
+		$product->save();
+
+		$selected_slug = get_term( $second_term_id )->slug;
+		$variation     = new WC_Product_Variation();
+		$variation->set_parent_id( $product->get_id() );
+		$variation->set_attributes( array( $taxonomy => $selected_slug ) );
+		$variation->save();
+		$attachment_id = $this->factory->post->create(
+			array(
+				'post_type'      => 'attachment',
+				'post_mime_type' => 'image/jpeg',
+			)
+		);
+		update_post_meta( $attachment_id, '_wp_attachment_image_alt', 'Original image text' );
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/' . $product->get_id() . '/variations/batch' );
+		$request->set_body_params(
+			array(
+				'update' => array(
+					array(
+						'id'         => $variation->get_id(),
+						'image'      => array(
+							'id'  => $attachment_id,
+							'alt' => 'Changed by rejected request',
+						),
+						'attributes' => array(
+							array(
+								'id'      => $attribute['attribute_id'],
+								'term_id' => $sign * $first_term_id + $offset,
+							),
+						),
+					),
+				),
+			)
+		);
+		$data = $this->server->dispatch( $request )->get_data();
+
+		$this->assertSame( 'woocommerce_rest_invalid_attribute_term_id', $data['update'][0]['error']['code'] ?? null, 'The term ID should be rejected.' );
+		$this->assertSame( $selected_slug, wc_get_product( $variation->get_id() )->get_attributes()[ $taxonomy ], 'The saved selection should not change.' );
+		$this->assertSame( 'Original image text', get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), 'Rejected requests must not update attachment metadata.' );
+	}
+
+	/**
+	 * @testdox A variation batch update skips malformed attribute entries while applying valid term selections.
+	 * @testWith [null]
+	 *           [false]
+	 *           [42]
+	 *           ["invalid"]
+	 *
+	 * @param mixed $invalid_attribute Non-array attribute entry.
+	 */
+	public function test_batch_update_variation_skips_non_array_attributes( $invalid_attribute ): void {
+		list( $attribute, $first_term_id, $second_term_id ) = $this->create_attribute_with_duplicate_term_names();
+		$taxonomy          = $attribute['attribute_taxonomy'];
+		$product_attribute = new WC_Product_Attribute();
+		$product_attribute->set_id( $attribute['attribute_id'] );
+		$product_attribute->set_name( $taxonomy );
+		$product_attribute->set_options( array( $first_term_id, $second_term_id ) );
+		$product_attribute->set_variation( true );
+		$product = new WC_Product_Variable();
+		$product->set_attributes( array( $product_attribute ) );
+		$product->save();
+
+		$variation = new WC_Product_Variation();
+		$variation->set_parent_id( $product->get_id() );
+		$variation->set_attributes( array( $taxonomy => get_term( $first_term_id )->slug ) );
+		$variation->save();
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/' . $product->get_id() . '/variations/batch' );
+		$request->set_body_params(
+			array(
+				'update' => array(
+					array(
+						'id'         => $variation->get_id(),
+						'attributes' => array(
+							$invalid_attribute,
+							array(
+								'id'      => $attribute['attribute_id'],
+								'term_id' => $second_term_id,
+							),
+							$invalid_attribute,
+						),
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+		$data     = $response->get_data();
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertSame( $variation->get_id(), $data['update'][0]['id'] );
+		$this->assertArrayNotHasKey( 'error', $data['update'][0] );
+		$this->assertSame( get_term( $second_term_id )->slug, wc_get_product( $variation->get_id() )->get_attributes()[ $taxonomy ] );
+	}
+
+	/**
+	 * @testdox An array option rejects only its variation batch item without changing saved data or images.
+	 * @testWith [false, false]
+	 *           [true, false]
+	 *           [false, true]
+	 *
+	 * @param bool $use_term_id Whether to include a valid term ID alongside the invalid option.
+	 * @param bool $custom_attribute Whether to use a custom attribute instead of a global attribute.
+	 */
+	public function test_batch_update_variation_rejects_array_option( bool $use_term_id, bool $custom_attribute ): void {
+		if ( $custom_attribute ) {
+			$product          = $this->create_customs_product_with_variation_attribute();
+			$taxonomy         = 'size';
+			$selected_option  = 'Small';
+			$posted_attribute = array( 'name' => 'Size' );
+		} else {
+			list( $attribute, $first_term_id, $second_term_id ) = $this->create_attribute_with_duplicate_term_names();
+			$taxonomy          = $attribute['attribute_taxonomy'];
+			$selected_option   = get_term( $first_term_id )->slug;
+			$product_attribute = new WC_Product_Attribute();
+			$product_attribute->set_id( $attribute['attribute_id'] );
+			$product_attribute->set_name( $taxonomy );
+			$product_attribute->set_options( array( $first_term_id, $second_term_id ) );
+			$product_attribute->set_variation( true );
+			$product = new WC_Product_Variable();
+			$product->set_attributes( array( $product_attribute ) );
+			$product->save();
+			$posted_attribute = array( 'id' => $attribute['attribute_id'] );
+			if ( $use_term_id ) {
+				$posted_attribute['term_id'] = $second_term_id;
+			}
+		}
+		$posted_attribute['option'] = array( 'Invalid option' );
+		$variations                 = array();
+		for ( $index = 0; $index < 3; ++$index ) {
+			$variation = new WC_Product_Variation();
+			$variation->set_parent_id( $product->get_id() );
+			$variation->set_attributes( array( $taxonomy => $selected_option ) );
+			$variation->set_description( 'Original description' );
+			$variation->save();
+			$variations[] = $variation;
+		}
+		$attachment_id = $this->factory->post->create(
+			array(
+				'post_type'      => 'attachment',
+				'post_mime_type' => 'image/jpeg',
+				'meta_input'     => array( '_wp_attached_file' => 'variation.jpg' ),
+			)
+		);
+		update_post_meta( $attachment_id, '_wp_attachment_image_alt', 'Original image text' );
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/' . $product->get_id() . '/variations/batch' );
+		$request->set_body_params(
+			array(
+				'update' => array(
+					array(
+						'id'          => $variations[0]->get_id(),
+						'description' => 'Updated before invalid item',
+					),
+					array(
+						'id'          => $variations[1]->get_id(),
+						'description' => 'Must not be saved',
+						'attributes'  => array( $posted_attribute ),
+						'image'       => array(
+							'id'  => $attachment_id,
+							'alt' => 'Changed by rejected request',
+						),
+					),
+					array(
+						'id'          => $variations[2]->get_id(),
+						'description' => 'Updated after invalid item',
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+		$data     = $response->get_data();
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertCount( 3, $data['update'] );
+		$this->assertSame( $variations[0]->get_id(), $data['update'][0]['id'] );
+		$this->assertSame( 'woocommerce_rest_invalid_attribute_option', $data['update'][1]['error']['code'] );
+		$this->assertSame( 400, $data['update'][1]['error']['data']['status'] );
+		$this->assertSame( $variations[2]->get_id(), $data['update'][2]['id'] );
+		$this->assertSame( 'Updated before invalid item', wc_get_product( $variations[0]->get_id() )->get_description() );
+		$this->assertSame( 'Original description', wc_get_product( $variations[1]->get_id() )->get_description() );
+		$this->assertSame( $selected_option, wc_get_product( $variations[1]->get_id() )->get_attributes()[ $taxonomy ] );
+		$this->assertSame( 'Original image text', get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) );
+		$this->assertSame( 'Updated after invalid item', wc_get_product( $variations[2]->get_id() )->get_description() );
+	}
+
+	/**
+	 * Creates a global attribute with two terms that share the name "Green" but have different slugs.
+	 *
+	 * @return array{0: array, 1: int, 2: int} Attribute data, first term ID, second term ID.
+	 */
+	private function create_attribute_with_duplicate_term_names(): array {
+		$attribute = WC_Helper_Product::create_attribute( 'color', array() );
+		$first     = wp_insert_term( 'Green', $attribute['attribute_taxonomy'], array( 'slug' => 'shirts-green' ) );
+		$second    = wp_insert_term( 'Green', $attribute['attribute_taxonomy'], array( 'slug' => 'trousers-green' ) );
+
+		return array( $attribute, $first['term_id'], $second['term_id'] );
+	}
 }
diff --git a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller-tests.php b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller-tests.php
index 6dae41e08fb..8528c6ff718 100644
--- a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller-tests.php
+++ b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-products-controller-tests.php
@@ -3346,4 +3346,181 @@ class WC_REST_Products_Controller_Tests extends WC_Unit_Test_Case {
 		$this->assertSame( $fields['description'], $post->post_content, 'The stored description should keep its backslash.' );
 		$this->assertSame( $fields['short_description'], $post->post_excerpt, 'The stored short description should keep its backslash.' );
 	}
+
+	/**
+	 * @testdox Global attribute terms can be set by ID, so terms that share a name are not mixed up.
+	 */
+	public function test_create_product_with_attribute_term_ids(): void {
+		list( $attribute, , $second_term_id ) = $this->create_attribute_with_duplicate_term_names();
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products' );
+		$request->set_body_params(
+			array(
+				'name'       => 'Trousers',
+				'attributes' => array(
+					array(
+						'id'       => $attribute['attribute_id'],
+						'term_ids' => array( $second_term_id ),
+						'options'  => array( 'Green' ),
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 201, $response->get_status() );
+		$terms = wc_get_product_terms( $response->get_data()['id'], $attribute['attribute_taxonomy'], array( 'fields' => 'slugs' ) );
+		$this->assertSame( array( 'trousers-green' ), $terms );
+	}
+
+	/**
+	 * @testdox An unknown attribute term ID is rejected instead of clearing the product's terms.
+	 */
+	public function test_create_product_with_unknown_attribute_term_id_fails(): void {
+		list( $attribute ) = $this->create_attribute_with_duplicate_term_names();
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products' );
+		$request->set_body_params(
+			array(
+				'name'       => 'Trousers',
+				'attributes' => array(
+					array(
+						'id'       => $attribute['attribute_id'],
+						'term_ids' => array( PHP_INT_MAX ),
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 400, $response->get_status() );
+		$this->assertSame( 'woocommerce_rest_invalid_attribute_term_id', $response->get_data()['code'] );
+	}
+
+	/**
+	 * @testdox An invalid attribute term ID is rejected instead of selecting a different term.
+	 * @testWith ["negative"]
+	 *           ["fractional"]
+	 *           ["scalar"]
+	 *           ["null"]
+	 *           ["unknown_attribute"]
+	 *           ["missing_attribute"]
+	 *
+	 * @param string $scenario Invalid term-ID payload to submit.
+	 */
+	public function test_batch_update_product_rejects_negative_attribute_term_id( string $scenario ): void {
+		list( $attribute, $first_term_id, $second_term_id ) = $this->create_attribute_with_duplicate_term_names();
+		$taxonomy = $attribute['attribute_taxonomy'];
+
+		$product_attribute = new WC_Product_Attribute();
+		$product_attribute->set_id( $attribute['attribute_id'] );
+		$product_attribute->set_name( $taxonomy );
+		$product_attribute->set_options( array( $second_term_id ) );
+		$product = WC_Helper_Product::create_simple_product();
+		$product->set_attributes( array( $product_attribute ) );
+		$product->save();
+
+		$unknown_term = 'unknown_attribute' === $scenario ? $this->factory->term->create( array( 'taxonomy' => 'product_cat' ) ) : 0;
+		$term_ids     = array(
+			'negative'          => array( -$first_term_id ),
+			'fractional'        => array( $first_term_id + 0.5 ),
+			'scalar'            => $first_term_id,
+			'null'              => null,
+			'unknown_attribute' => array( $unknown_term ),
+			'missing_attribute' => array( $first_term_id ),
+		)[ $scenario ];
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/batch' );
+		$request->set_body_params(
+			array(
+				'update' => array(
+					array(
+						'id'         => $product->get_id(),
+						'attributes' => array(
+							array(
+								'id'       => 'unknown_attribute' === $scenario ? PHP_INT_MAX : ( 'missing_attribute' === $scenario ? 0 : $attribute['attribute_id'] ),
+								'name'     => 'Color',
+								'term_ids' => $term_ids,
+							),
+						),
+					),
+				),
+			)
+		);
+		$data = $this->server->dispatch( $request )->get_data();
+
+		$this->assertSame( 'woocommerce_rest_invalid_attribute_term_id', $data['update'][0]['error']['code'] ?? null, 'The invalid term ID should be rejected.' );
+		$this->assertSame( array( $second_term_id ), wc_get_product_terms( $product->get_id(), $taxonomy, array( 'fields' => 'ids' ) ), 'The product terms should not change.' );
+	}
+
+	/**
+	 * @testdox A malformed attribute rejects only its batch item and preserves its saved product data.
+	 * @testWith [null]
+	 *           [false]
+	 *           [42]
+	 *           ["invalid"]
+	 *
+	 * @param mixed $invalid_attribute Non-array attribute entry.
+	 */
+	public function test_batch_update_continues_after_non_array_attribute( $invalid_attribute ): void {
+		list( $attribute, $term_id ) = $this->create_attribute_with_duplicate_term_names();
+		$product_attribute           = new WC_Product_Attribute();
+		$product_attribute->set_id( $attribute['attribute_id'] );
+		$product_attribute->set_name( $attribute['attribute_taxonomy'] );
+		$product_attribute->set_options( array( $term_id ) );
+
+		$before  = WC_Helper_Product::create_simple_product();
+		$product = WC_Helper_Product::create_simple_product();
+		$product->set_attributes( array( $product_attribute ) );
+		$product->save();
+		$original_name = $product->get_name();
+		$after         = WC_Helper_Product::create_simple_product();
+
+		$request = new WP_REST_Request( 'POST', '/wc/v3/products/batch' );
+		$request->set_body_params(
+			array(
+				'update' => array(
+					array(
+						'id'   => $before->get_id(),
+						'name' => 'Updated before invalid item',
+					),
+					array(
+						'id'         => $product->get_id(),
+						'name'       => 'Must not be saved',
+						'attributes' => array( $invalid_attribute ),
+					),
+					array(
+						'id'   => $after->get_id(),
+						'name' => 'Updated after invalid item',
+					),
+				),
+			)
+		);
+		$response = $this->server->dispatch( $request );
+		$data     = $response->get_data();
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertCount( 3, $data['update'] );
+		$this->assertSame( $before->get_id(), $data['update'][0]['id'] );
+		$this->assertSame( 'woocommerce_rest_invalid_attribute', $data['update'][1]['error']['code'] );
+		$this->assertSame( 400, $data['update'][1]['error']['data']['status'] );
+		$this->assertSame( $after->get_id(), $data['update'][2]['id'] );
+		$this->assertSame( 'Updated before invalid item', wc_get_product( $before->get_id() )->get_name() );
+		$this->assertSame( $original_name, wc_get_product( $product->get_id() )->get_name() );
+		$this->assertSame( array( $term_id ), wc_get_product_terms( $product->get_id(), $attribute['attribute_taxonomy'], array( 'fields' => 'ids' ) ) );
+		$this->assertSame( 'Updated after invalid item', wc_get_product( $after->get_id() )->get_name() );
+	}
+
+	/**
+	 * Creates a global attribute with two terms that share the name "Green" but have different slugs.
+	 *
+	 * @return array{0: array, 1: int, 2: int} Attribute data, first term ID, second term ID.
+	 */
+	private function create_attribute_with_duplicate_term_names(): array {
+		$attribute = WC_Helper_Product::create_attribute( 'color', array() );
+		$first     = wp_insert_term( 'Green', $attribute['attribute_taxonomy'], array( 'slug' => 'shirts-green' ) );
+		$second    = wp_insert_term( 'Green', $attribute['attribute_taxonomy'], array( 'slug' => 'trousers-green' ) );
+
+		return array( $attribute, $first['term_id'], $second['term_id'] );
+	}
 }