Commit c62b7716bc0 for woocommerce

commit c62b7716bc09d675d81771536bcef9fa04829310
Author: Aarón Fas <yo@aaron.com.es>
Date:   Wed Dec 2 13:17:49 2026 +0100

    Paginate order search in SQL for the posts-storage ability (#71543)

    * Share posts-storage order search SQL

    Keep the matching rules in the posts data store reusable by paginated queries. Direct searches still feed the full ID list, in the existing match order, to extensions before returning it.

    * Paginate posts-storage ability searches in SQL

    A common search term could build an ID list for the entire store before fetching one page. Join the distinct matches to the ability query so its filters, sort order and totals apply across all matches.

    * Add changelog entry for paginated order search

    Let merchants using posts storage know that broad ability searches use less PHP memory.

    * Remove obsolete order search PHPStan baseline entry

    The extracted search query no longer passes nested arrays to implode. Keeping its old exception makes the full PHPStan run fail on an unmatched baseline entry.

    * Guard the order search join when a caller omits the query

    A caller can invoke posts_join with only its SQL fragment. Preserve that fragment when the callback has no query to inspect.

    * Exercise nonmatches and duplicate matches in order search pagination

    Give the pagination fixture one unrelated order and an order matching two search sources so skipped filtering or duplicate rows break the assertions.

    * Mark order search helper methods internal

    Match the HPOS search helper so the API boundary is visible when reading individual method documentation.

diff --git a/plugins/woocommerce/changelog/task-wooai-1670-bound-the-order-search-on-posts-storage-in-the-orders-query b/plugins/woocommerce/changelog/task-wooai-1670-bound-the-order-search-on-posts-storage-in-the-orders-query
new file mode 100644
index 00000000000..74f7164ecbd
--- /dev/null
+++ b/plugins/woocommerce/changelog/task-wooai-1670-bound-the-order-search-on-posts-storage-in-the-orders-query
@@ -0,0 +1,4 @@
+Significance: patch
+Type: performance
+
+Reduce memory use for broad searches with the orders query ability on stores using posts storage.
diff --git a/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php b/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
index 92859a8497c..9aa9158e88e 100644
--- a/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
+++ b/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
@@ -5,6 +5,7 @@
  * @package WooCommerce\Classes
  */

+use Automattic\WooCommerce\Internal\DataStores\Orders\OrderSearchQuery;
 use Automattic\WooCommerce\Enums\OrderStatus;
 use Automattic\WooCommerce\Enums\OrderInternalStatus;
 use Automattic\WooCommerce\Utilities\OrderUtil;
@@ -575,78 +576,7 @@ class WC_Order_Data_Store_CPT extends Abstract_WC_Order_Data_Store_CPT implement
 	 * @return array of ids
 	 */
 	public function search_orders( $term ) {
-		global $wpdb;
-
-		/**
-		 * Searches on meta data can be slow - this lets you choose what fields to search.
-		 * 3.0.0 added _billing_address and _shipping_address meta which contains all address data to make this faster.
-		 * This however won't work on older orders unless updated, so search a few others (expand this using the filter if needed).
-		 *
-		 * @var array
-		 */
-		$search_fields = array_map(
-			'wc_clean',
-			apply_filters(
-				'woocommerce_shop_order_search_fields',
-				array(
-					'_billing_address_index',
-					'_shipping_address_index',
-					'_billing_last_name',
-					'_billing_email',
-					'_billing_phone',
-				)
-			)
-		);
-		$order_ids     = array();
-
-		if ( is_numeric( $term ) ) {
-			$order_ids[] = absint( $term );
-		}
-
-		if ( ! empty( $search_fields ) ) {
-			$order_ids = array_unique(
-				array_merge(
-					$order_ids,
-					$wpdb->get_col(
-						$wpdb->prepare(
-							"SELECT DISTINCT p1.post_id FROM {$wpdb->postmeta} p1 WHERE p1.meta_value LIKE %s AND p1.meta_key IN ('" . implode( "','", array_map( 'esc_sql', $search_fields ) ) . "')", // @codingStandardsIgnoreLine
-							'%' . $wpdb->esc_like( wc_clean( $term ) ) . '%'
-						)
-					),
-					$wpdb->get_col(
-						$wpdb->prepare(
-							"SELECT order_id
-							FROM {$wpdb->prefix}woocommerce_order_items as order_items
-							WHERE order_item_name LIKE %s",
-							'%' . $wpdb->esc_like( wc_clean( $term ) ) . '%'
-						)
-					),
-					$wpdb->get_col(
-						$wpdb->prepare(
-							"SELECT DISTINCT os.order_id FROM {$wpdb->prefix}wc_order_stats os
-							INNER JOIN {$wpdb->prefix}wc_customer_lookup cl ON os.customer_id = cl.customer_id
-							INNER JOIN {$wpdb->usermeta} um ON cl.user_id = um.user_id
-							WHERE (um.meta_key = 'billing_phone' OR um.meta_key = 'shipping_phone')
-							AND um.meta_value = %s",
-							wc_clean( $term )
-						)
-					)
-				)
-			);
-		}
-
-		/**
-		 * Filter the order ids to be returned.
-		 *
-		 * @since 3.0.0
-		 * @param array $order_ids The order ids.
-		 * @param string $term The search term.
-		 * @param array $search_fields The search fields.
-		 * @return array
-		 */
-		$order_ids = apply_filters( 'woocommerce_shop_order_search_results', $order_ids, $term, $search_fields );
-
-		return array_map( 'absint', $order_ids );
+		return ( new OrderSearchQuery( $term ) )->get_ids();
 	}

 	/**
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 123a7faa965..66fa4780039 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -16633,12 +16633,6 @@ parameters:
 			count: 1
 			path: includes/data-stores/class-wc-order-data-store-cpt.php

-		-
-			message: '#^Parameter \#2 \$array of function implode expects array\<string\>, array\<array\|string\> given\.$#'
-			identifier: argument.type
-			count: 1
-			path: includes/data-stores/class-wc-order-data-store-cpt.php
-
 		-
 			message: '#^Parameter \#3 \$index_key of function wp_list_pluck expects int\|string\|null, true given\.$#'
 			identifier: argument.type
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 231b2b8633e..917c2512474 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -165,6 +165,8 @@ class AbilitiesLoader {
 		add_filter( 'woocommerce_product_data_store_cpt_get_products_query', array( __CLASS__, 'add_extension_query_args' ), 10, 2 );
 		add_filter( 'woocommerce_order_data_store_cpt_get_orders_query', array( __CLASS__, 'add_extension_query_args' ), 10, 2 );

+		add_filter( 'posts_join', array( OrdersQuery::class, 'join_search_matches' ), 10, 2 );
+
 		self::$initialized = true;
 	}

diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrdersQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrdersQuery.php
index 81a19ad85db..a8d9fa343e5 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/OrdersQuery.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrdersQuery.php
@@ -11,6 +11,7 @@ use Automattic\WooCommerce\Abilities\AbilityDefinition;
 use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
 use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
 use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\OrderAbilityTrait;
+use Automattic\WooCommerce\Internal\DataStores\Orders\OrderSearchQuery;
 use Automattic\WooCommerce\Utilities\OrderUtil;

 defined( 'ABSPATH' ) || exit;
@@ -22,6 +23,8 @@ class OrdersQuery extends AbstractDomainAbility implements AbilityDefinition {

 	use OrderAbilityTrait;

+	private const SEARCH_QUERY_VAR = 'wc_orders_ability_search';
+
 	/**
 	 * Get the ability name.
 	 *
@@ -208,9 +211,9 @@ class OrdersQuery extends AbstractDomainAbility implements AbilityDefinition {
 			if ( $hpos ) {
 				$args['s'] = $search;
 			} else {
-				// Posts storage matches `s` against post title and content only, which orders leave empty.
-				$matches = wc_order_search( $search );
-				$include = null === $include ? $matches : array_intersect( $include, $matches );
+				$args[ self::SEARCH_QUERY_VAR ] = $search;
+				// Changes to customer phone or order items can affect matches without invalidating the post query cache.
+				$args['cache_results'] = false;
 			}
 		}
 		if ( null !== $include ) {
@@ -265,6 +268,30 @@ class OrdersQuery extends AbstractDomainAbility implements AbilityDefinition {
 		);
 	}

+	/**
+	 * Join matching order IDs before WP_Query counts and pages the orders.
+	 *
+	 * @internal
+	 * @param string         $join  Existing JOIN clauses.
+	 * @param \WP_Query|null $query WordPress posts query, if supplied.
+	 * @return string
+	 */
+	public static function join_search_matches( $join, $query = null ) {
+		global $wpdb;
+
+		if ( ! $query instanceof \WP_Query ) {
+			return $join;
+		}
+
+		$term = $query->get( self::SEARCH_QUERY_VAR );
+		if ( ! is_string( $term ) || '' === $term ) {
+			return $join;
+		}
+
+		$matches = ( new OrderSearchQuery( $term ) )->get_subquery();
+		return $join . " INNER JOIN ( $matches ) AS wc_order_matches ON wc_order_matches.order_id = {$wpdb->posts}.ID ";
+	}
+
 	/**
 	 * Check order read access.
 	 *
diff --git a/plugins/woocommerce/src/Internal/DataStores/Orders/OrderSearchQuery.php b/plugins/woocommerce/src/Internal/DataStores/Orders/OrderSearchQuery.php
new file mode 100644
index 00000000000..ac202d91b39
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/DataStores/Orders/OrderSearchQuery.php
@@ -0,0 +1,144 @@
+<?php
+/**
+ * Order search on posts storage.
+ *
+ * @package WooCommerce
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\DataStores\Orders;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Builds the order ID matches used by posts-storage searches.
+ *
+ * @internal
+ */
+class OrderSearchQuery {
+	/**
+	 * Search term passed to the results filter.
+	 *
+	 * @var string
+	 */
+	private $term;
+
+	/**
+	 * Filtered order metadata keys.
+	 *
+	 * @var string[]
+	 */
+	private $fields;
+
+	/**
+	 * Exact ID match for numeric search terms.
+	 *
+	 * @var int|null
+	 */
+	private $id;
+
+	/**
+	 * Prepared statements returning matching IDs in legacy search order.
+	 *
+	 * @var string[]
+	 */
+	private $queries = array();
+
+	/**
+	 * Prepare the searches for a cleaned order search term.
+	 *
+	 * @internal
+	 *
+	 * @param string $term Cleaned search term.
+	 */
+	public function __construct( $term ) {
+		global $wpdb;
+
+		$this->term = $term;
+		$this->id   = is_numeric( $term ) ? absint( $term ) : null;
+		/**
+		 * Filters the order meta keys searched on posts storage.
+		 *
+		 * @since 1.5.6
+		 * @param string[] $fields Order meta keys.
+		 */
+		$fields       = apply_filters(
+			'woocommerce_shop_order_search_fields',
+			array( '_billing_address_index', '_shipping_address_index', '_billing_last_name', '_billing_email', '_billing_phone' )
+		);
+		$this->fields = array_map( 'sanitize_text_field', $fields );
+		if ( empty( $this->fields ) ) {
+			return;
+		}
+
+		$term         = wc_clean( $term );
+		$like         = '%' . $wpdb->esc_like( $term ) . '%';
+		$placeholders = implode( ', ', array_fill( 0, count( $this->fields ), '%s' ) );
+
+		$this->queries = array(
+			$wpdb->prepare(
+				"SELECT DISTINCT post_id AS order_id FROM {$wpdb->postmeta} WHERE meta_value LIKE %s AND meta_key IN ( $placeholders )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Only %s placeholders.
+				array_merge( array( $like ), array_values( $this->fields ) )
+			),
+			$wpdb->prepare(
+				"SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_name LIKE %s",
+				$like
+			),
+			$wpdb->prepare(
+				"SELECT DISTINCT os.order_id FROM {$wpdb->prefix}wc_order_stats os
+				INNER JOIN {$wpdb->prefix}wc_customer_lookup cl ON os.customer_id = cl.customer_id
+				INNER JOIN {$wpdb->usermeta} um ON cl.user_id = um.user_id
+				WHERE um.meta_key IN ( 'billing_phone', 'shipping_phone' ) AND um.meta_value = %s",
+				$term
+			),
+		);
+	}
+
+	/**
+	 * Returns a single-column subquery for use before sorting and pagination.
+	 *
+	 * @internal
+	 *
+	 * @return string
+	 */
+	public function get_subquery() {
+		global $wpdb;
+		$queries = $this->queries;
+		if ( null !== $this->id ) {
+			$queries[] = $wpdb->prepare( 'SELECT %d AS order_id', $this->id );
+		}
+		return $queries ? implode( ' UNION ', $queries ) : 'SELECT NULL AS order_id';
+	}
+
+	/**
+	 * Returns the full list for callers of wc_order_search().
+	 *
+	 * @internal
+	 *
+	 * @return int[]
+	 */
+	public function get_ids() {
+		global $wpdb;
+		$matches = array( null === $this->id ? array() : array( $this->id ) );
+		foreach ( $this->queries as $query ) {
+			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Each statement is prepared in the constructor.
+			$matches[] = $wpdb->get_col( $query );
+		}
+		$order_ids = array_unique( array_merge( ...$matches ) );
+		unset( $matches );
+
+		/**
+		 * Filter the order ids to be returned.
+		 *
+		 * @since 3.0.0
+		 * @param array $order_ids The order ids.
+		 * @param string $term The search term.
+		 * @param array $search_fields The search fields.
+		 * @return array
+		 */
+		$order_ids = apply_filters( 'woocommerce_shop_order_search_results', $order_ids, $this->term, $this->fields );
+
+		return array_map( 'absint', $order_ids );
+	}
+}
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/order/class-wc-tests-order-functions.php b/plugins/woocommerce/tests/legacy/unit-tests/order/class-wc-tests-order-functions.php
index f0da7a44e1b..b99cc0e7c7b 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/order/class-wc-tests-order-functions.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/order/class-wc-tests-order-functions.php
@@ -1978,6 +1978,37 @@ class WC_Tests_Order_Functions extends WC_Unit_Test_Case {
 		$this->assertEmpty( wc_order_search( 'Nonexistent term' ) );
 	}

+	/**
+	 * Posts-storage extensions can replace the full ID list and choose the fields to search.
+	 */
+	public function test_posts_order_search_filters() {
+		$first  = self::factory()->post->create( array( 'post_type' => 'shop_order' ) );
+		$second = self::factory()->post->create( array( 'post_type' => 'shop_order' ) );
+		foreach ( array( $first, $second ) as $id ) {
+			add_post_meta( $id, '_invoice_number', 'Invoice-123' );
+		}
+
+		$fields  = static function () {
+			return array( '_invoice_number' );
+		};
+		$results = function ( $ids, $term, $search_fields ) use ( $first, $second ) {
+			$this->assertEqualsCanonicalizing( array( $first, $second ), $ids );
+			$this->assertSame( 'Invoice-123', $term );
+			$this->assertSame( array( '_invoice_number' ), $search_fields );
+			return array( $second );
+		};
+
+		add_filter( 'woocommerce_shop_order_search_fields', $fields );
+		add_filter( 'woocommerce_shop_order_search_results', $results, 10, 3 );
+		try {
+			$store = new WC_Order_Data_Store_CPT();
+			$this->assertSame( array( $second ), $store->search_orders( 'Invoice-123' ) );
+		} finally {
+			remove_filter( 'woocommerce_shop_order_search_results', $results );
+			remove_filter( 'woocommerce_shop_order_search_fields', $fields );
+		}
+	}
+
 	/**
 	 * Checks if hold coupons are released when increasing usage count.
 	 *
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrdersQueryTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrdersQueryTest.php
index 937dc617ef6..34145c9a4dd 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrdersQueryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrdersQueryTest.php
@@ -206,6 +206,64 @@ class OrdersQueryTest extends WC_Unit_Test_Case {
 		}
 	}

+	/**
+	 * @testdox The order search join tolerates callers that omit the posts query.
+	 */
+	public function test_posts_join_without_query(): void {
+		$this->assertSame( 'existing join', apply_filters( 'posts_join', 'existing join' ) );
+	}
+
+	/**
+	 * @testdox Posts storage pages all search matches even when the legacy ID-list filter replaces its results.
+	 */
+	public function test_posts_search_pages_matches_in_the_order_query(): void {
+		$this->use_storage( false );
+		$first  = $this->create_customer_order( 'Zoe', 'Jones', 'zoe@example.com', 'Zebra mug' );
+		$second = $this->create_customer_order( 'Zac', 'Smith', 'zac@example.com' );
+		$third  = $this->create_customer_order( 'Zara', 'Shaw', 'zara@example.com' );
+		$this->create_customer_order( 'Jane', 'Doe', 'jane@example.com' );
+
+		$args = array(
+			'search'   => 'z',
+			'per_page' => 2,
+			'orderby'  => 'id',
+			'order'    => 'asc',
+		);
+
+		add_filter( 'woocommerce_shop_order_search_results', '__return_empty_array' );
+		try {
+			$page_one = OrdersQuery::execute( $args );
+			$page_two = OrdersQuery::execute( array_merge( $args, array( 'page' => 2 ) ) );
+		} finally {
+			remove_filter( 'woocommerce_shop_order_search_results', '__return_empty_array' );
+		}
+
+		$this->assertSame( array( $first, $second ), array_column( $page_one['orders'], 'id' ) );
+		$this->assertSame( array( $third ), array_column( $page_two['orders'], 'id' ) );
+		$this->assertSame( 3, $page_one['total'] );
+		$this->assertSame( 3, $page_two['total'] );
+		$this->assertSame( 2, $page_one['total_pages'] );
+		$this->assertSame( 2, $page_two['total_pages'] );
+	}
+
+	/**
+	 * @testdox Updating a customer's phone changes matches without an order edit.
+	 */
+	public function test_posts_search_reflects_customer_phone_changes(): void {
+		$this->use_storage( false );
+		$customer = self::factory()->user->create( array( 'role' => 'customer' ) );
+		$order    = $this->create_customer_order( 'Jane', 'Doe', 'jane@example.com', null, $customer );
+		\Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore::sync_order( $order );
+
+		$args   = array( 'search' => '555-0199' );
+		$before = OrdersQuery::execute( $args );
+		update_user_meta( $customer, 'shipping_phone', '555-0199' );
+		$after = OrdersQuery::execute( $args );
+
+		$this->assertSame( array(), $before['orders'] );
+		$this->assertSame( array( $order ), array_column( $after['orders'], 'id' ) );
+	}
+
 	/**
 	 * @testdox Should find an order by its order number, with or without an "Order #" prefix.
 	 *