Commit ff0340881f5 for woocommerce

commit ff0340881f5db067595834b16ce0dcb52b071e5d
Author: Daniel Kam <hey@danielk.am>
Date:   Wed Nov 18 00:57:23 2026 +0800

    REST API: Add slug param to wc/v3/products/attributes so it returns only matches (#69318)

    * Add slug filter to the v3 product attributes REST endpoint

    * Add changelog entry for product attributes slug filter

    * Fix analytics attribute searches ignoring the slug filter

    * Update changelog for analytics attribute slug filtering

    * Fix product attribute slug validation and analytics matching

    * Return numeric custom attribute slugs as strings

    * Fix numeric custom attribute slug lookups

    * Fix custom attribute lookup edge cases

    * Omit misleading numeric custom attribute self links

    * Simplify numeric custom attribute key detection

    * Omit custom attribute links that item lookup cannot resolve

    * Restore product attribute PR to slug filter scope

diff --git a/docs/apis/rest-api/v3/product-attributes.mdx b/docs/apis/rest-api/v3/product-attributes.mdx
index 5ec4a3a9bea..91ce03ddfde 100644
--- a/docs/apis/rest-api/v3/product-attributes.mdx
+++ b/docs/apis/rest-api/v3/product-attributes.mdx
@@ -324,9 +324,10 @@ woocommerce.get("products/attributes").parsed_response

 #### Available parameters

-| Parameter | Type   | Description                                                                                                                  |
-| --------- | ------ | ---------------------------------------------------------------------------------------------------------------------------- |
-| `context` | string | Scope under which the request is made; determines fields present in response. Options: `view` and `edit`. Default is `view`. |
+| Parameter | Type            | Description                                                                                                                                                  |
+| --------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `context` | string          | Scope under which the request is made; determines fields present in response. Options: `view` and `edit`. Default is `view`.                                 |
+| `slug`    | string or array | Limit result set to attributes with a specific slug, for example `pa_color` or `color`. Pass an array, such as `slug[]=color&slug[]=size`, to match several. |

 ## Update a product attribute

diff --git a/plugins/woocommerce/changelog/29625-product-attributes-slug-filter b/plugins/woocommerce/changelog/29625-product-attributes-slug-filter
new file mode 100644
index 00000000000..0fa9d919eb3
--- /dev/null
+++ b/plugins/woocommerce/changelog/29625-product-attributes-slug-filter
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Allow filtering product attributes by slug in the REST API, including analytics attribute searches.
diff --git a/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php b/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php
index f12e3d6103e..b3797ddd072 100644
--- a/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php
+++ b/plugins/woocommerce/includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php
@@ -237,7 +237,7 @@ class WC_REST_Product_Attributes_V1_Controller extends WC_REST_Controller {
 	 * Get all attributes.
 	 *
 	 * @param WP_REST_Request $request The request to get the attributes from.
-	 * @return array
+	 * @return WP_REST_Response
 	 */
 	public function get_items( $request ) {
 		$attributes = wc_get_attribute_taxonomies();
diff --git a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller.php b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller.php
index 48ad7ce28ca..dc7c6836758 100644
--- a/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller.php
+++ b/plugins/woocommerce/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller.php
@@ -52,6 +52,91 @@ class WC_REST_Product_Attributes_Controller extends WC_REST_Product_Attributes_V
 		return $root_slug . '-' . ( $suffix + 1 );
 	}

+	/**
+	 * Get all attributes, limited to the requested slugs when the `slug` parameter is set.
+	 *
+	 * @since 11.4.0 Supports the `slug` parameter.
+	 *
+	 * @param WP_REST_Request<array<string, mixed>> $request The request to get the attributes from.
+	 * @return WP_REST_Response
+	 */
+	public function get_items( $request ) {
+		$attributes     = wc_get_attribute_taxonomies();
+		$taxonomy_names = $this->get_requested_taxonomy_names( $request );
+
+		if ( ! empty( $taxonomy_names ) ) {
+			$attributes = array_filter(
+				$attributes,
+				static function ( $attribute ) use ( $taxonomy_names ) {
+					return in_array( wc_attribute_taxonomy_name( $attribute->attribute_name ), $taxonomy_names, true );
+				}
+			);
+		}
+
+		$data = array();
+		foreach ( $attributes as $attribute_obj ) {
+			$attribute = $this->prepare_item_for_response( $attribute_obj, $request );
+			$data[]    = $this->prepare_response_for_collection( $attribute );
+		}
+
+		$response = rest_ensure_response( $data );
+
+		// All matching attributes are returned at once, so there is only ever one page.
+		$response->header( 'X-WP-Total', (string) count( $data ) );
+		$response->header( 'X-WP-TotalPages', '1' );
+
+		return $response;
+	}
+
+	/**
+	 * Get the attribute taxonomy names (the `slug` field of the response) requested in the `slug` parameter.
+	 *
+	 * Slugs are normalized the same way as on create, so `pa_color`, `color` and `Color` all become `pa_color`.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @param WP_REST_Request<array<string, mixed>> $request Full details about the request.
+	 * @return string[] Taxonomy names, or an empty array when no slug was requested.
+	 */
+	protected function get_requested_taxonomy_names( $request ) {
+		$taxonomy_names = array();
+
+		foreach ( (array) $request['slug'] as $slug ) {
+			if ( '' !== $slug ) {
+				$taxonomy_names[] = wc_attribute_taxonomy_name( wc_attribute_taxonomy_slug( $slug ) );
+			}
+		}
+
+		return array_unique( $taxonomy_names );
+	}
+
+	/**
+	 * Get the query params for collections.
+	 *
+	 * @since 11.4.0
+	 *
+	 * @return array
+	 */
+	public function get_collection_params() {
+		$params         = parent::get_collection_params();
+		$params['slug'] = array(
+			'description'       => __( 'Limit result set to attributes with a specific slug. The "pa_" prefix is optional.', 'woocommerce' ),
+			'type'              => array( 'string', 'array' ),
+			'items'             => array(
+				'type' => 'string',
+			),
+			'validate_callback' => static function ( $value, $request, $param ) {
+				if ( ! is_string( $value ) && ! is_array( $value ) ) {
+					return false;
+				}
+
+				return rest_validate_request_arg( $value, $request, $param );
+			},
+		);
+
+		return $params;
+	}
+
 	/**
 	 * Create a single attribute.
 	 *
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 40024da958c..fadb0795899 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -23544,11 +23544,6 @@ parameters:
 			count: 1
 			path: includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php

-		-
-			message: '#^Method WC_REST_Product_Attributes_V1_Controller\:\:get_items\(\) should return array but returns WP_REST_Response\.$#'
-			identifier: return.type
-			count: 1
-			path: includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php

 		-
 			message: '#^Method WC_REST_Product_Attributes_V1_Controller\:\:get_items_permissions_check\(\) has parameter \$request with generic class WP_REST_Request but does not specify its types\: T$#'
@@ -23628,11 +23623,6 @@ parameters:
 			count: 1
 			path: includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php

-		-
-			message: '#^Return type \(array\) of method WC_REST_Product_Attributes_V1_Controller\:\:get_items\(\) should be compatible with return type \(WP_Error\|WP_REST_Response\) of method WP_REST_Controller\:\:get_items\(\)$#'
-			identifier: method.childReturnType
-			count: 1
-			path: includes/rest-api/Controllers/Version1/class-wc-rest-product-attributes-v1-controller.php

 		-
 			message: '#^Cannot access property \$post_date_gmt on WP_Post\|null\.$#'
@@ -38631,11 +38621,6 @@ parameters:
 			count: 1
 			path: src/Admin/API/ProductAttributeTerms.php

-		-
-			message: '#^Access to offset ''search'' on an unknown class Automattic\\WooCommerce\\Admin\\API\\WP_REST_Request\.$#'
-			identifier: class.notFound
-			count: 2
-			path: src/Admin/API/ProductAttributes.php

 		-
 			message: '#^Access to offset ''slug'' on an unknown class Automattic\\WooCommerce\\Admin\\API\\WP_REST_Request\.$#'
@@ -38667,23 +38652,8 @@ parameters:
 			count: 1
 			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Method Automattic\\WooCommerce\\Admin\\API\\ProductAttributes\:\:get_items\(\) has invalid return type Automattic\\WooCommerce\\Admin\\API\\WP_REST_Response\.$#'
-			identifier: class.notFound
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Method Automattic\\WooCommerce\\Admin\\API\\ProductAttributes\:\:get_items\(\) should return Automattic\\WooCommerce\\Admin\\API\\WP_REST_Response but returns WP_REST_Response\.$#'
-			identifier: return.type
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Method Automattic\\WooCommerce\\Admin\\API\\ProductAttributes\:\:get_items\(\) should return Automattic\\WooCommerce\\Admin\\API\\WP_REST_Response but returns array\.$#'
-			identifier: return.type
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

 		-
 			message: '#^Method Automattic\\WooCommerce\\Admin\\API\\ProductAttributes\:\:register_routes\(\) has no return type specified\.$#'
@@ -38715,17 +38685,7 @@ parameters:
 			count: 1
 			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Parameter \#1 \$request of method WC_REST_Product_Attributes_V1_Controller\:\:get_items\(\) expects WP_REST_Request, Automattic\\WooCommerce\\Admin\\API\\WP_REST_Request given\.$#'
-			identifier: argument.type
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Parameter \#2 \$request of method WC_REST_Product_Attributes_V1_Controller\:\:prepare_item_for_response\(\) expects WP_REST_Request, Automattic\\WooCommerce\\Admin\\API\\WP_REST_Request given\.$#'
-			identifier: argument.type
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

 		-
 			message: '#^Parameter \#2 \$value of method WP_HTTP_Response\:\:header\(\) expects string, int given\.$#'
@@ -38745,17 +38705,7 @@ parameters:
 			count: 1
 			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Parameter \$request of method Automattic\\WooCommerce\\Admin\\API\\ProductAttributes\:\:get_items\(\) has invalid type Automattic\\WooCommerce\\Admin\\API\\WP_REST_Request\.$#'
-			identifier: class.notFound
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

-		-
-			message: '#^Return type \(Automattic\\WooCommerce\\Admin\\API\\WP_REST_Response\) of method Automattic\\WooCommerce\\Admin\\API\\ProductAttributes\:\:get_items\(\) should be compatible with return type \(array\) of method WC_REST_Product_Attributes_V1_Controller\:\:get_items\(\)$#'
-			identifier: method.childReturnType
-			count: 1
-			path: src/Admin/API/ProductAttributes.php

 		-
 			message: '#^PHPDoc tag @extends has invalid value \(WC_REST_Product_Categories_Controller\)\: Unexpected token "\\n ", expected ''\<'' at offset 103 on line 5$#'
diff --git a/plugins/woocommerce/src/Admin/API/ProductAttributes.php b/plugins/woocommerce/src/Admin/API/ProductAttributes.php
index a82963e9d00..f3425745033 100644
--- a/plugins/woocommerce/src/Admin/API/ProductAttributes.php
+++ b/plugins/woocommerce/src/Admin/API/ProductAttributes.php
@@ -136,16 +136,30 @@ class ProductAttributes extends \WC_REST_Product_Attributes_Controller {
 	/**
 	 * Get all attributes, with support for searching (which includes custom attributes).
 	 *
-	 * @param WP_REST_Request $request The API request.
-	 * @return WP_REST_Response
+	 * @param \WP_REST_Request<array<string, mixed>> $request The API request.
+	 * @return \WP_REST_Response
 	 */
 	public function get_items( $request ) {
 		if ( empty( $request['search'] ) ) {
 			return parent::get_items( $request );
 		}

-		$search_string       = $request['search'];
-		$custom_attributes   = $this->get_custom_attributes( array( 'name' => $search_string ) );
+		$search_string     = $request['search'];
+		$taxonomy_names    = $this->get_requested_taxonomy_names( $request );
+		$custom_attributes = $this->get_custom_attributes( array( 'name' => $search_string ) );
+
+		if ( ! empty( $taxonomy_names ) ) {
+			$custom_slugs      = array_map( 'sanitize_title', (array) $request['slug'] );
+			$custom_attributes = array_filter(
+				$custom_attributes,
+				static function ( $slug ) use ( $custom_slugs ) {
+					$slug = (string) $slug;
+					return 0 !== strpos( $slug, 'pa_' ) && in_array( $slug, $custom_slugs, true );
+				},
+				ARRAY_FILTER_USE_KEY
+			);
+		}
+
 		$matching_attributes = $this->format_custom_attribute_items_for_response( $custom_attributes );
 		$taxonomy_attributes = wc_get_attribute_taxonomies();

@@ -155,6 +169,10 @@ class ProductAttributes extends \WC_REST_Product_Attributes_Controller {
 				continue;
 			}

+			if ( ! empty( $taxonomy_names ) && ! in_array( wc_attribute_taxonomy_name( $attribute_obj->attribute_name ), $taxonomy_names, true ) ) {
+				continue;
+			}
+
 			$attribute             = $this->prepare_item_for_response( $attribute_obj, $request );
 			$matching_attributes[] = $this->prepare_response_for_collection( $attribute );
 		}
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/product-attributes.php b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/product-attributes.php
index 0064124c1f1..cbd3d161d68 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/product-attributes.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/product-attributes.php
@@ -74,6 +74,16 @@ class WC_Admin_Tests_API_Product_Attributes extends WC_REST_Unit_Test_Case {
 			$custom_attr->set_variation( true );
 			$attributes[] = $custom_attr;

+			$custom_colour = new WC_Product_Attribute();
+			$custom_colour->set_name( 'Colour' );
+			$custom_colour->set_options( array( 'red', 'blue' ) );
+			$attributes[] = $custom_colour;
+
+			$custom_numeric = new WC_Product_Attribute();
+			$custom_numeric->set_name( '123' );
+			$custom_numeric->set_options( array( 'example' ) );
+			$attributes[] = $custom_numeric;
+
 			$product->set_attributes( $attributes );
 			$product->save();

@@ -219,6 +229,69 @@ class WC_Admin_Tests_API_Product_Attributes extends WC_REST_Unit_Test_Case {
 		$this->assertContains( 'Numeric Size', $names );
 	}

+	/**
+	 * @testdox Search intersects global and custom attribute matches with the requested slugs.
+	 * @testWith ["pa_number", ["pa_number"]]
+	 *           ["NUMBER", ["pa_number"]]
+	 *           ["numeric-size", ["numeric-size"]]
+	 *           [["PA_Number", "numeric-size"], ["numeric-size", "pa_number"]]
+	 *           ["pa_colour", []]
+	 *           ["colour", []]
+	 *           ["does-not-exist", []]
+	 *           ["", ["numeric-size", "pa_number"]]
+	 *           [[], ["numeric-size", "pa_number"]]
+	 *
+	 * @param string|string[] $slug Requested slugs.
+	 * @param string[]        $expected_slugs Expected response slugs.
+	 */
+	public function test_search_with_slug( $slug, array $expected_slugs ): void {
+		wp_set_current_user( $this->user );
+
+		$request = new WP_REST_Request( 'GET', $this->endpoint );
+		$request->set_query_params(
+			array(
+				'search' => 'num',
+				'slug'   => $slug,
+			)
+		);
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertSame( $expected_slugs, wp_list_pluck( $response->get_data(), 'slug' ) );
+		$this->assertSame( count( $expected_slugs ), $response->get_headers()['X-WP-Total'] );
+		$this->assertSame( 1, $response->get_headers()['X-WP-TotalPages'] );
+	}
+
+	/**
+	 * @testdox Prefixed slugs select only global attributes, while unprefixed slugs can select both kinds.
+	 * @testWith ["Colour", "pa_colour", ["pa_colour"]]
+	 *           ["Colour", "PA_Colour", ["pa_colour"]]
+	 *           ["Colour", "colour", ["colour", "pa_colour"]]
+	 *           ["Colour", ["pa_colour", "colour"], ["colour", "pa_colour"]]
+	 *           ["num", "pa_numeric-size", []]
+	 *           ["123", "123", [123]]
+	 *
+	 * @param string          $search Search term.
+	 * @param string|string[] $slug Requested slugs.
+	 * @param string[]|int[]  $expected_slugs Expected response slugs.
+	 */
+	public function test_search_distinguishes_global_and_custom_slugs( string $search, $slug, array $expected_slugs ): void {
+		wp_set_current_user( $this->user );
+
+		$request = new WP_REST_Request( 'GET', $this->endpoint );
+		$request->set_query_params(
+			array(
+				'search' => $search,
+				'slug'   => $slug,
+			)
+		);
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertSame( $expected_slugs, wp_list_pluck( $response->get_data(), 'slug' ) );
+		$this->assertSame( count( $expected_slugs ), $response->get_headers()['X-WP-Total'] );
+	}
+
 	/**
 	 * Test getting a single attribute by slug.
 	 */
diff --git a/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller-tests.php b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller-tests.php
new file mode 100644
index 00000000000..8e7db970e07
--- /dev/null
+++ b/plugins/woocommerce/tests/php/includes/rest-api/Controllers/Version3/class-wc-rest-product-attributes-controller-tests.php
@@ -0,0 +1,98 @@
+<?php
+declare( strict_types = 1 );
+
+/**
+ * class WC_REST_Product_Attributes_Controller_Tests.
+ * Product Attributes Controller tests for V3 REST API.
+ */
+class WC_REST_Product_Attributes_Controller_Tests extends WC_REST_Unit_Test_Case {
+
+	/**
+	 * Set up test fixtures.
+	 */
+	public function setUp(): void {
+		parent::setUp();
+
+		wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) );
+
+		// Names other tests don't use: wc_create_attribute() fails if the pa_* taxonomy is already registered.
+		foreach ( array( 'Strap Color', 'Lens Size', 'Frame Material' ) as $name ) {
+			$this->assertIsInt( wc_create_attribute( array( 'name' => $name ) ), "The {$name} attribute fixture should be created" );
+		}
+	}
+
+	/**
+	 * @testdox Should limit the attributes list to the requested slugs, with or without the "pa_" prefix.
+	 *
+	 * @testWith ["pa_strap-color", ["pa_strap-color"]]
+	 *           ["strap-color", ["pa_strap-color"]]
+	 *           ["PA_Strap-Color", ["pa_strap-color"]]
+	 *           [["strap-color", "pa_lens-size"], ["pa_lens-size", "pa_strap-color"]]
+	 *           [["strap-color", "pa_strap-color"], ["pa_strap-color"]]
+	 *           ["does-not-exist", []]
+	 *           ["pa_", []]
+	 *
+	 * @param string|string[] $slug           Value of the slug parameter.
+	 * @param string[]        $expected_slugs Slugs expected in the response, in order.
+	 */
+	public function test_get_items_filters_by_slug( $slug, array $expected_slugs ): void {
+		$request = new WP_REST_Request( 'GET', '/wc/v3/products/attributes' );
+		$request->set_param( 'slug', $slug );
+
+		$response = $this->server->dispatch( $request );
+		$headers  = $response->get_headers();
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertSame( $expected_slugs, wp_list_pluck( $response->get_data(), 'slug' ), 'The response should only contain the requested attributes' );
+		$this->assertEquals( count( $expected_slugs ), $headers['X-WP-Total'], 'X-WP-Total should count the filtered attributes' );
+		$this->assertEquals( 1, $headers['X-WP-TotalPages'] );
+	}
+
+	/**
+	 * @testdox Should return every attribute when the slug parameter is missing or empty.
+	 *
+	 * @testWith [null]
+	 *           [""]
+	 *
+	 * @param string|null $slug Value of the slug parameter, or null to leave it out.
+	 */
+	public function test_get_items_returns_all_attributes_without_slug( ?string $slug ): void {
+		$request = new WP_REST_Request( 'GET', '/wc/v3/products/attributes' );
+		if ( null !== $slug ) {
+			$request->set_param( 'slug', $slug );
+		}
+
+		$response = $this->server->dispatch( $request );
+		$slugs    = wp_list_pluck( $response->get_data(), 'slug' );
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertCount( count( wc_get_attribute_taxonomies() ), $slugs, 'Every attribute should be returned' );
+		foreach ( array( 'pa_frame-material', 'pa_lens-size', 'pa_strap-color' ) as $fixture_slug ) {
+			$this->assertContains( $fixture_slug, $slugs );
+		}
+		$this->assertEquals( count( $slugs ), $response->get_headers()['X-WP-Total'] );
+	}
+
+	/**
+	 * @testdox Should reject a slug parameter that is not a string or a list of strings.
+	 *
+	 * @testWith [42]
+	 *           [true]
+	 *           [false]
+	 *           [1.5]
+	 *           [[42]]
+	 *           [["strap-color", 42]]
+	 *           [[["strap-color"]]]
+	 *
+	 * @param mixed $slug Invalid slug parameter.
+	 */
+	public function test_get_items_rejects_invalid_slug_param( $slug ): void {
+		$request = new WP_REST_Request( 'GET', '/wc/v3/products/attributes' );
+		$request->set_param( 'slug', $slug );
+
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 400, $response->get_status() );
+		$this->assertSame( 'rest_invalid_param', $response->get_data()['code'] );
+	}
+}