-
Notifications
You must be signed in to change notification settings - Fork 0
/
woocommerce.0003.fix.product-finder-filters.patch
493 lines (462 loc) · 18.2 KB
/
woocommerce.0003.fix.product-finder-filters.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
From 060ca167f881a58dd56cca661d96191cbf2664aa Mon Sep 17 00:00:00 2001
From: Fabian Marz <[email protected]>
Date: Thu, 11 Jan 2024 13:00:05 +0100
Subject: [PATCH] Fixed product finder filters were not showing correct
results.
---
.../Routes/V1/ProductCollectionData.php | 55 +++-
.../Utilities/ProductQueryFilters.php | 287 ++++--------------
2 files changed, 105 insertions(+), 237 deletions(-)
diff --git a/packages/woocommerce-blocks/src/StoreApi/Routes/V1/ProductCollectionData.php b/packages/woocommerce-blocks/src/StoreApi/Routes/V1/ProductCollectionData.php
index 169113744..88fbc99db 100644
--- a/packages/woocommerce-blocks/src/StoreApi/Routes/V1/ProductCollectionData.php
+++ b/packages/woocommerce-blocks/src/StoreApi/Routes/V1/ProductCollectionData.php
@@ -91,12 +91,49 @@ class ProductCollectionData extends AbstractRoute {
}
if ( ! empty( $request['calculate_attribute_counts'] ) ) {
+ $taxonomy__or_queries = [];
+ $taxonomy__and_queries = [];
+
foreach ( $request['calculate_attribute_counts'] as $attributes_to_count ) {
- if ( ! isset( $attributes_to_count['taxonomy'] ) ) {
- continue;
+ if ( ! empty( $attributes_to_count['taxonomy'] ) ) {
+ if ( empty( $attributes_to_count['query_type'] ) || 'or' === $attributes_to_count['query_type'] ) {
+ $taxonomy__or_queries[] = $attributes_to_count['taxonomy'];
+ } else {
+ $taxonomy__and_queries[] = $attributes_to_count['taxonomy'];
+ }
}
+ }
+
+ $data['attribute_counts'] = [];
+ // Or type queries need special handling because the attribute, if set, needs removing from the query first otherwise counts would not be correct.
+ if ( $taxonomy__or_queries ) {
+ foreach ( $taxonomy__or_queries as $taxonomy ) {
+ $filter_request = clone $request;
+ $filter_attributes = $filter_request->get_param( 'attributes' );
+
+ if ( ! empty( $filter_attributes ) ) {
+ $filter_attributes = array_filter(
+ $filter_attributes,
+ function( $query ) use ( $taxonomy ) {
+ return $query['attribute'] !== $taxonomy;
+ }
+ );
+ }
+
+ $filter_request->set_param( 'attributes', $filter_attributes );
+ $counts = $filters->get_attribute_counts( $filter_request, [ $taxonomy ] );
+
+ foreach ( $counts as $key => $value ) {
+ $data['attribute_counts'][] = (object) [
+ 'term' => $key,
+ 'count' => $value,
+ ];
+ }
+ }
+ }
- $counts = $filters->get_attribute_counts( $request, $attributes_to_count['taxonomy'] );
+ if ( $taxonomy__and_queries ) {
+ $counts = $filters->get_attribute_counts( $request, $taxonomy__and_queries );
foreach ( $counts as $key => $value ) {
$data['attribute_counts'][] = (object) [
@@ -132,31 +169,31 @@ class ProductCollectionData extends AbstractRoute {
$params = ( new Products( $this->schema_controller, $this->schema ) )->get_collection_params();
$params['calculate_price_range'] = [
- 'description' => __( 'If true, calculates the minimum and maximum product prices for the collection.', 'woocommerce' ),
+ 'description' => __( 'If true, calculates the minimum and maximum product prices for the collection.', 'woo-gutenberg-products-block' ),
'type' => 'boolean',
'default' => false,
];
$params['calculate_stock_status_counts'] = [
- 'description' => __( 'If true, calculates stock counts for products in the collection.', 'woocommerce' ),
+ 'description' => __( 'If true, calculates stock counts for products in the collection.', 'woo-gutenberg-products-block' ),
'type' => 'boolean',
'default' => false,
];
$params['calculate_attribute_counts'] = [
- 'description' => __( 'If requested, calculates attribute term counts for products in the collection.', 'woocommerce' ),
+ 'description' => __( 'If requested, calculates attribute term counts for products in the collection.', 'woo-gutenberg-products-block' ),
'type' => 'array',
'items' => [
'type' => 'object',
'properties' => [
'taxonomy' => [
- 'description' => __( 'Taxonomy name.', 'woocommerce' ),
+ 'description' => __( 'Taxonomy name.', 'woo-gutenberg-products-block' ),
'type' => 'string',
'context' => [ 'view', 'edit' ],
'readonly' => true,
],
'query_type' => [
- 'description' => __( 'Filter condition being performed which may affect counts. Valid values include "and" and "or".', 'woocommerce' ),
+ 'description' => __( 'Filter condition being performed which may affect counts. Valid values include "and" and "or".', 'woo-gutenberg-products-block' ),
'type' => 'string',
'enum' => [ 'and', 'or' ],
'context' => [ 'view', 'edit' ],
@@ -168,7 +205,7 @@ class ProductCollectionData extends AbstractRoute {
];
$params['calculate_rating_counts'] = [
- 'description' => __( 'If true, calculates rating counts for products in the collection.', 'woocommerce' ),
+ 'description' => __( 'If true, calculates rating counts for products in the collection.', 'woo-gutenberg-products-block' ),
'type' => 'boolean',
'default' => false,
];
diff --git a/packages/woocommerce-blocks/src/StoreApi/Utilities/ProductQueryFilters.php b/packages/woocommerce-blocks/src/StoreApi/Utilities/ProductQueryFilters.php
index abe87390c..22dfd9817 100644
--- a/packages/woocommerce-blocks/src/StoreApi/Utilities/ProductQueryFilters.php
+++ b/packages/woocommerce-blocks/src/StoreApi/Utilities/ProductQueryFilters.php
@@ -2,9 +2,6 @@
namespace Automattic\WooCommerce\StoreApi\Utilities;
use Automattic\WooCommerce\StoreApi\Utilities\ProductQuery;
-use Exception;
-use WP_REST_Request;
-
/**
* Product Query filters class.
@@ -114,196 +111,63 @@ class ProductQueryFilters {
}
/**
- * Get terms list for a given taxonomy.
- *
- * @param string $taxonomy Taxonomy name.
- *
- * @return array
- */
- public function get_terms_list( string $taxonomy ) {
- global $wpdb;
-
- return $wpdb->get_results(
- $wpdb->prepare(
- "SELECT term_id as term_count_id,
- count(DISTINCT product_or_parent_id) as term_count
- FROM {$wpdb->prefix}wc_product_attributes_lookup
- WHERE taxonomy = %s
- GROUP BY term_id",
- $taxonomy
- )
- );
- }
-
- /**
- * Get the empty terms list for a given taxonomy.
- *
- * @param string $taxonomy Taxonomy name.
+ * Get attribute counts for the current products.
*
- * @return array
+ * @param \WP_REST_Request $request The request object.
+ * @param array $attributes Attributes to count, either names or ids.
+ * @return array termId=>count pairs.
*/
- public function get_empty_terms_list( string $taxonomy ) {
+ public function get_attribute_counts( $request, $attributes = [] ) {
global $wpdb;
- return $wpdb->get_results(
- $wpdb->prepare(
- "SELECT DISTINCT term_id as term_count_id,
- 0 as term_count
- FROM {$wpdb->prefix}wc_product_attributes_lookup
- WHERE taxonomy = %s",
- $taxonomy
- )
- );
- }
-
- /**
- * Get attribute and meta counts.
- *
- * @param WP_REST_Request $request Request data.
- * @param string $filtered_attribute The attribute to count.
- *
- * @return array
- */
- public function get_attribute_counts( $request, $filtered_attribute ) {
- if ( is_array( $filtered_attribute ) ) {
- wc_deprecated_argument( 'attributes', 'TBD', 'get_attribute_counts does not require an array of attributes as the second parameter anymore. Provide the filtered attribute as a string instead.' );
-
- $filtered_attribute = ! empty( $filtered_attribute[0] ) ? $filtered_attribute[0] : '';
-
- if ( empty( $filtered_attribute ) ) {
- return array();
- }
- }
-
- $attributes_data = $request->get_param( 'attributes' );
- $calculate_attribute_counts = $request->get_param( 'calculate_attribute_counts' );
- $min_price = $request->get_param( 'min_price' );
- $max_price = $request->get_param( 'max_price' );
- $rating = $request->get_param( 'rating' );
- $stock_status = $request->get_param( 'stock_status' );
-
- $transient_key = 'wc_get_attribute_and_meta_counts_' . md5(
- wp_json_encode(
- array(
- 'attributes_data' => $attributes_data,
- 'calculate_attribute_counts' => $calculate_attribute_counts,
- 'min_price' => $min_price,
- 'max_price' => $max_price,
- 'rating' => $rating,
- 'stock_status' => $stock_status,
- 'filtered_attribute' => $filtered_attribute,
- )
- )
- );
-
- $cached_results = get_transient( $transient_key );
- if ( ! empty( $cached_results ) && defined( 'WP_DEBUG' ) && ! WP_DEBUG ) {
- return $cached_results;
- }
-
- if ( empty( $attributes_data ) && empty( $min_price ) && empty( $max_price ) && empty( $rating ) && empty( $stock_status ) ) {
- $counts = $this->get_terms_list( $filtered_attribute );
-
- return array_map( 'absint', wp_list_pluck( $counts, 'term_count', 'term_count_id' ) );
- }
-
- $where_clause = '';
- if ( ! empty( $min_price ) || ! empty( $max_price ) || ! empty( $rating ) || ! empty( $stock_status ) ) {
- $product_metas = [
- 'min_price' => $min_price,
- 'max_price' => $max_price,
- 'average_rating' => $rating,
- 'stock_status' => $stock_status,
- ];
-
- $filtered_products_by_metas = $this->get_product_by_metas( $product_metas );
- $formatted_filtered_products_by_metas = implode( ',', array_map( 'intval', $filtered_products_by_metas ) );
-
- if ( ! empty( $formatted_filtered_products_by_metas ) ) {
- if ( ! empty( $rating ) ) {
- $where_clause .= sprintf( ' AND product_attribute_lookup.product_or_parent_id IN (%1s)', $formatted_filtered_products_by_metas );
- } else {
- $where_clause .= sprintf( ' AND product_attribute_lookup.product_id IN (%1s)', $formatted_filtered_products_by_metas );
- }
- } else {
- $counts = $this->get_empty_terms_list( $filtered_attribute );
-
- return array_map( 'absint', wp_list_pluck( $counts, 'term_count', 'term_count_id' ) );
- }
- }
-
- $join_type = 'LEFT';
- foreach ( $attributes_data as $attribute ) {
- $filtered_terms = $attribute['slug'] ?? '';
-
- if ( empty( $filtered_terms ) ) {
- continue;
- }
-
- $taxonomy = $attribute['attribute'] ?? '';
- $term_ids = [];
- if ( in_array( $taxonomy, wc_get_attribute_taxonomy_names(), true ) ) {
- foreach ( $filtered_terms as $filtered_term ) {
- $term = get_term_by( 'slug', $filtered_term, $taxonomy );
- if ( is_object( $term ) ) {
- $term_ids[] = $term->term_id;
- }
- }
- }
+ // Remove paging and sorting params from the request.
+ $request->set_param( 'page', null );
+ $request->set_param( 'per_page', null );
+ $request->set_param( 'order', null );
+ $request->set_param( 'orderby', null );
- if ( empty( $term_ids ) ) {
- continue;
- }
+ // Grab the request from the WP Query object, and remove SQL_CALC_FOUND_ROWS and Limits so we get a list of all products.
+ $product_query = new ProductQuery();
- foreach ( $calculate_attribute_counts as $calculate_attribute_count ) {
- if ( ! isset( $calculate_attribute_count['taxonomy'] ) && ! isset( $calculate_attribute_count['query_type'] ) ) {
- continue;
- }
+ add_filter( 'posts_clauses', array( $product_query, 'add_query_clauses' ), 10, 2 );
+ add_filter( 'posts_pre_query', '__return_empty_array' );
- $query_type = $calculate_attribute_count['query_type'];
- $filtered_products_by_terms = $this->get_product_by_filtered_terms( $calculate_attribute_count['taxonomy'], $term_ids, $query_type );
- $formatted_filtered_products_by_terms = implode( ',', array_map( 'intval', $filtered_products_by_terms ) );
+ $query_args = $product_query->prepare_objects_query( $request );
+ $query_args['no_found_rows'] = true;
+ $query_args['posts_per_page'] = -1;
+ $query = new \WP_Query();
+ $result = $query->query( $query_args );
+ $product_query_sql = $query->request;
- if ( ! empty( $formatted_filtered_products_by_terms ) ) {
- $where_clause .= sprintf( ' AND product_attribute_lookup.product_or_parent_id IN (%1s)', $formatted_filtered_products_by_terms );
- }
+ remove_filter( 'posts_clauses', array( $product_query, 'add_query_clauses' ), 10 );
+ remove_filter( 'posts_pre_query', '__return_empty_array' );
- if ( $calculate_attribute_count['taxonomy'] === $filtered_attribute ) {
- $join_type = 'or' === $query_type ? 'LEFT' : 'INNER';
- }
- }
+ if ( count( $attributes ) === count( array_filter( $attributes, 'is_numeric' ) ) ) {
+ $attributes = array_map( 'wc_attribute_taxonomy_name_by_id', wp_parse_id_list( $attributes ) );
}
- global $wpdb;
- $counts = $wpdb->get_results(
- // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
- $wpdb->prepare(
- "
- SELECT attributes.term_id as term_count_id, coalesce(term_count, 0) as term_count
- FROM (SELECT DISTINCT term_id
- FROM {$wpdb->prefix}wc_product_attributes_lookup
- WHERE taxonomy = %s) as attributes %1s JOIN (
- SELECT COUNT(DISTINCT product_attribute_lookup.product_or_parent_id) as term_count, product_attribute_lookup.term_id
- FROM {$wpdb->prefix}wc_product_attributes_lookup product_attribute_lookup
- INNER JOIN {$wpdb->posts} posts
- ON posts.ID = product_attribute_lookup.product_id
- WHERE posts.post_type IN ('product', 'product_variation') AND posts.post_status = 'publish'%1s
- GROUP BY product_attribute_lookup.term_id
- ) summarize
- ON attributes.term_id = summarize.term_id
- ",
- $filtered_attribute,
- $join_type,
- $where_clause
- )
+ $attributes_to_count = array_map(
+ function( $attribute ) {
+ $attribute = wc_sanitize_taxonomy_name( $attribute );
+ return esc_sql( $attribute );
+ },
+ $attributes
);
+ $attributes_to_count_sql = 'AND term_taxonomy.taxonomy IN ("' . implode( '","', $attributes_to_count ) . '")';
+ $attribute_count_sql = "
+ SELECT COUNT( DISTINCT posts.ID ) as term_count, terms.term_id as term_count_id
+ FROM {$wpdb->posts} AS posts
+ INNER JOIN {$wpdb->term_relationships} AS term_relationships ON posts.ID = term_relationships.object_id
+ INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id )
+ INNER JOIN {$wpdb->terms} AS terms USING( term_id )
+ WHERE posts.ID IN ( {$product_query_sql} )
+ {$attributes_to_count_sql}
+ GROUP BY terms.term_id
+ ";
- // phpcs:enable
- $results = array_map( 'absint', wp_list_pluck( $counts, 'term_count', 'term_count_id' ) );
-
- set_transient( $transient_key, $results, 24 * HOUR_IN_SECONDS );
+ $results = $wpdb->get_results( $attribute_count_sql ); // phpcs:ignore
- return $results;
+ return array_map( 'absint', wp_list_pluck( $results, 'term_count', 'term_count_id' ) );
}
/**
@@ -365,64 +229,33 @@ class ProductQueryFilters {
$where = array();
$results = array();
$params = array();
- foreach ( $metas as $column => $value ) {
- if ( empty( $value ) ) {
- continue;
- }
-
- if ( 'stock_status' === $column ) {
- $stock_product_ids = array();
- foreach ( $value as $stock_status ) {
- $stock_product_ids[] = $wpdb->get_col(
- $wpdb->prepare(
- "SELECT DISTINCT product_id FROM {$wpdb->prefix}wc_product_meta_lookup WHERE stock_status = %s",
- $stock_status
- )
- );
- }
-
- $where[] = 'product_id IN (' . implode( ',', array_merge( ...$stock_product_ids ) ) . ')';
- continue;
- }
+ foreach ( $metas as $column => $value ) {
if ( 'min_price' === $column ) {
- $where[] = "{$column} >= %d";
- $params[] = intval( $value ) / 100;
+ $where[] = "{$column} >= %f";
+ $params[] = (float) $value;
continue;
}
if ( 'max_price' === $column ) {
- $where[] = "{$column} <= %d";
- $params[] = intval( $value ) / 100;
+ $where[] = "{$column} <= %f";
+ $params[] = (float) $value;
continue;
}
- if ( 'average_rating' === $column ) {
- $where_rating = array();
- foreach ( $value as $rating ) {
- $where_rating[] = sprintf( '(average_rating >= %f - 0.5 AND average_rating < %f + 0.5)', $rating, $rating );
- }
- $where[] = '(' . implode( ' OR ', $where_rating ) . ')';
- continue;
- }
-
- $where[] = sprintf( "%1s = '%s'", $column, $value );
+ $where[] = "{$column} = %s";
$params[] = $value;
}
if ( ! empty( $where ) ) {
$where_clause = implode( ' AND ', $where );
- $where_clause = sprintf( $where_clause, ...$params );
-
- // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
+ // Use a parameterized query.
$results = $wpdb->get_col(
- $wpdb->prepare(
- "SELECT DISTINCT product_id FROM {$wpdb->prefix}wc_product_meta_lookup WHERE %1s",
- $where_clause
+ $wpdb->prepare( "SELECT DISTINCT product_id FROM {$wpdb->prefix}wc_product_meta_lookup WHERE {$where_clause}", // phpcs:ignore
+ $params
)
);
}
- // phpcs:enable
return $results;
}
@@ -444,40 +277,38 @@ class ProductQueryFilters {
$term_ids = implode( ',', array_map( 'intval', $term_ids ) );
if ( 'or' === $query_type ) {
+ // phpcs:disable
$results = $wpdb->get_col(
- // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
$wpdb->prepare(
"
SELECT DISTINCT `product_or_parent_id`
FROM {$wpdb->prefix}wc_product_attributes_lookup
WHERE `taxonomy` = %s
- AND `term_id` IN (%1s)
+ AND `term_id` IN ({$term_ids})
",
- $taxonomy,
- $term_ids
+ $taxonomy
)
- // phpcs:enable
);
+ // phpcs:enable
}
if ( 'and' === $query_type ) {
+ // phpcs:disable
$results = $wpdb->get_col(
- // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
$wpdb->prepare(
"
SELECT DISTINCT `product_or_parent_id`
FROM {$wpdb->prefix}wc_product_attributes_lookup
WHERE `taxonomy` = %s
- AND `term_id` IN (%1s)
+ AND `term_id` IN ({$term_ids})
GROUP BY `product_or_parent_id`
HAVING COUNT( DISTINCT `term_id` ) >= %d
",
$taxonomy,
- $term_ids,
$term_count
)
- // phpcs:enable
);
+ // phpcs:enable
}
return $results;
--
2.30.2