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2.0-rc.1 3.0.9 6.2.0-rc.2 3.1.0 6.2.1 3.1.1 6.2.2 3.1.2 6.2.3 3.2.0 6.3.0 3.2.1 6.3.0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / src / StoreApi / Utilities / ProductQuery.php
woocommerce / src / StoreApi / Utilities Last commit date
AgenticCheckoutUtils.php 4 days ago ArrayUtils.php 2 years ago CartController.php 1 month ago CartTokenUtils.php 1 year ago CheckoutTrait.php 1 month ago DraftOrderTrait.php 1 year ago JsonWebToken.php 11 months ago LocalPickupUtils.php 5 months ago NoticeHandler.php 1 year ago OrderAuthorizationTrait.php 4 days ago OrderController.php 4 days ago Pagination.php 2 years ago PaymentUtils.php 1 year ago ProductItemTrait.php 1 month ago ProductLinksTrait.php 3 months ago ProductQuery.php 4 days ago ProductQueryFilters.php 4 days ago QuantityLimits.php 11 months ago RateLimits.php 1 year ago SanitizationUtils.php 2 years ago ValidationUtils.php 2 years ago
ProductQuery.php
635 lines
1 <?php
2 declare(strict_types=1);
3
4 namespace Automattic\WooCommerce\StoreApi\Utilities;
5
6 use Automattic\WooCommerce\Enums\ProductStatus;
7 use Automattic\WooCommerce\Enums\ProductType;
8 use Automattic\WooCommerce\Enums\CatalogVisibility;
9 use Automattic\WooCommerce\Enums\TaxDisplayMode;
10 use Automattic\WooCommerce\Internal\ProductFilters\Interfaces\QueryClausesGenerator;
11 use Automattic\WooCommerce\Internal\Utilities\ProductUtil;
12 use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
13 use WC_Tax;
14
15 /**
16 * Product Query class.
17 *
18 * Helper class to handle product queries for the API.
19 */
20 class ProductQuery implements QueryClausesGenerator {
21 /**
22 * Prepare query args to pass to WP_Query for a REST API request.
23 *
24 * @param \WP_REST_Request $request Request data.
25 * @return array
26 * @throws RouteException If the related product ID is invalid or the product is not visible.
27 */
28 public function prepare_objects_query( $request ) {
29 $args = array(
30 'offset' => $request['offset'],
31 'order' => $request['order'],
32 'orderby' => $request['orderby'],
33 'paged' => $request['page'],
34 'post__in' => $request['include'],
35 'post__not_in' => $request['exclude'],
36 'posts_per_page' => $request['per_page'] ? $request['per_page'] : -1,
37 'post_parent__in' => $request['parent'],
38 'post_parent__not_in' => $request['parent_exclude'],
39 'search' => $request['search'], // This uses search rather than s intentionally to handle searches internally.
40 'slug' => $request['slug'],
41 'fields' => 'ids',
42 'ignore_sticky_posts' => true,
43 'post_status' => ProductStatus::PUBLISH,
44 'date_query' => array(),
45 'post_type' => 'product',
46 );
47
48 // If searching for a specific SKU or slug, allow any post type.
49 if ( ! empty( $request['sku'] ) || ! empty( $request['slug'] ) ) {
50 $args['post_type'] = array( 'product', 'product_variation' );
51 }
52
53 // Taxonomy query to filter products by type, category, tag, shipping class, and attribute.
54 $tax_query = array();
55
56 // Filter product type by slug.
57 if ( ! empty( $request['type'] ) ) {
58 if ( ProductType::VARIATION === $request['type'] ) {
59 $args['post_type'] = 'product_variation';
60 } else {
61 $args['post_type'] = 'product';
62 $tax_query[] = array(
63 'taxonomy' => 'product_type',
64 'field' => 'slug',
65 'terms' => $request['type'],
66 );
67 }
68 }
69
70 if ( 'date' === $args['orderby'] ) {
71 $args['orderby'] = 'date ID';
72 }
73
74 // Set before into date query. Date query must be specified as an array of an array.
75 if ( isset( $request['before'] ) ) {
76 $args['date_query'][0]['before'] = $request['before'];
77 }
78
79 // Set after into date query. Date query must be specified as an array of an array.
80 if ( isset( $request['after'] ) ) {
81 $args['date_query'][0]['after'] = $request['after'];
82 }
83
84 // Set date query column. Defaults to post_date.
85 if ( isset( $request['date_column'] ) && ! empty( $args['date_query'][0] ) ) {
86 $args['date_query'][0]['column'] = 'post_' . $request['date_column'];
87 }
88
89 // Set custom args to handle later during clauses.
90 $custom_keys = array(
91 'sku',
92 'min_price',
93 'max_price',
94 'stock_status',
95 );
96
97 foreach ( $custom_keys as $key ) {
98 if ( ! empty( $request[ $key ] ) ) {
99 $args[ $key ] = $request[ $key ];
100 }
101 }
102
103 $operator_mapping = array(
104 'in' => 'IN',
105 'not_in' => 'NOT IN',
106 'and' => 'AND',
107 );
108
109 // Gets all registered product taxonomies and prefixes them with `tax_`.
110 // This is needed to avoid situations where a user registers a new product taxonomy with the same name as default field.
111 // eg an `sku` taxonomy will be mapped to `tax_sku`.
112 $all_product_taxonomies = array_map(
113 function ( $value ) {
114 return '_unstable_tax_' . $value;
115 },
116 get_taxonomies( array( 'object_type' => array( 'product' ) ), 'names' )
117 );
118
119 // Map between taxonomy name and arg key.
120 $default_taxonomies = array(
121 'product_cat' => 'category',
122 'product_tag' => 'tag',
123 'product_brand' => 'brand',
124 );
125
126 $taxonomies = array_merge( $all_product_taxonomies, $default_taxonomies );
127
128 // Set tax_query for each passed arg.
129 foreach ( $taxonomies as $taxonomy => $key ) {
130 if ( ! empty( $request[ $key ] ) ) {
131 $type = is_numeric( $request[ $key ][0] ) ? 'term_id' : 'slug';
132 $operator = $request->get_param( $key . '_operator' ) && isset( $operator_mapping[ $request->get_param( $key . '_operator' ) ] ) ? $operator_mapping[ $request->get_param( $key . '_operator' ) ] : 'IN';
133 $tax_query[] = array(
134 'taxonomy' => $taxonomy,
135 'field' => $type,
136 'terms' => $request[ $key ],
137 'operator' => $operator,
138 );
139 }
140 }
141
142 // Filter by attributes.
143 if ( ! empty( $request['attributes'] ) ) {
144 $att_queries = array();
145
146 foreach ( $request['attributes'] as $attribute ) {
147 if ( empty( $attribute['term_id'] ) && empty( $attribute['slug'] ) ) {
148 continue;
149 }
150 if ( in_array( $attribute['attribute'], wc_get_attribute_taxonomy_names(), true ) ) {
151 $operator = isset( $attribute['operator'], $operator_mapping[ $attribute['operator'] ] ) ? $operator_mapping[ $attribute['operator'] ] : 'IN';
152 $att_queries[] = array(
153 'taxonomy' => $attribute['attribute'],
154 'field' => ! empty( $attribute['term_id'] ) ? 'term_id' : 'slug',
155 'terms' => ! empty( $attribute['term_id'] ) ? $attribute['term_id'] : $attribute['slug'],
156 'operator' => $operator,
157 );
158 }
159 }
160
161 if ( 1 < count( $att_queries ) ) {
162 // Add relation arg when using multiple attributes.
163 $relation = $request->get_param( 'attribute_relation' ) && isset( $operator_mapping[ $request->get_param( 'attribute_relation' ) ] ) ? $operator_mapping[ $request->get_param( 'attribute_relation' ) ] : 'IN';
164 $tax_query[] = array(
165 'relation' => $relation,
166 $att_queries,
167 );
168 } else {
169 $tax_query = array_merge( $tax_query, $att_queries );
170 }
171 }
172
173 // Build tax_query if taxonomies are set.
174 if ( ! empty( $tax_query ) && 'product_variation' !== $args['post_type'] ) {
175 if ( ! empty( $args['tax_query'] ) ) {
176 $args['tax_query'] = array_merge( $tax_query, $args['tax_query'] ); // phpcs:ignore
177 } else {
178 $args['tax_query'] = $tax_query; // phpcs:ignore
179 }
180 } else {
181 // For product_variantions we need to convert the tax_query to a meta_query.
182 if ( ! empty( $args['tax_query'] ) ) {
183 $args['meta_query'] = $this->convert_tax_query_to_meta_query( array_merge( $tax_query, $args['tax_query'] ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
184 } else {
185 $args['meta_query'] = $this->convert_tax_query_to_meta_query( $tax_query ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
186 }
187 }
188
189 // Filter featured.
190 if ( is_bool( $request['featured'] ) ) {
191 $args['tax_query'][] = array(
192 'taxonomy' => 'product_visibility',
193 'field' => 'name',
194 'terms' => 'featured',
195 'operator' => true === $request['featured'] ? 'IN' : 'NOT IN',
196 );
197 }
198
199 // Filter by on sale products.
200 if ( is_bool( $request['on_sale'] ) ) {
201 $on_sale_key = $request['on_sale'] ? 'post__in' : 'post__not_in';
202 $on_sale_ids = wc_get_product_ids_on_sale();
203
204 // Use 0 when there's no on sale products to avoid return all products.
205 $on_sale_ids = empty( $on_sale_ids ) ? array( 0 ) : $on_sale_ids;
206
207 $args[ $on_sale_key ] += $on_sale_ids;
208 }
209
210 $catalog_visibility = $request->get_param( 'catalog_visibility' );
211 $rating = $request->get_param( 'rating' );
212 $visibility_options = wc_get_product_visibility_options();
213
214 if ( in_array( $catalog_visibility, array_keys( $visibility_options ), true ) ) {
215 $exclude_from_catalog = CatalogVisibility::SEARCH === $catalog_visibility ? '' : 'exclude-from-catalog';
216 $exclude_from_search = CatalogVisibility::CATALOG === $catalog_visibility ? '' : 'exclude-from-search';
217
218 $args['tax_query'][] = array(
219 'taxonomy' => 'product_visibility',
220 'field' => 'name',
221 'terms' => array( $exclude_from_catalog, $exclude_from_search ),
222 'operator' => CatalogVisibility::HIDDEN === $catalog_visibility ? 'AND' : 'NOT IN',
223 'rating_filter' => true,
224 );
225 }
226
227 if ( $rating ) {
228 $rating_terms = array();
229 foreach ( $rating as $value ) {
230 $rating_terms[] = 'rated-' . $value;
231 }
232 $args['tax_query'][] = array(
233 'taxonomy' => 'product_visibility',
234 'field' => 'name',
235 'terms' => $rating_terms,
236 );
237 }
238
239 $orderby = $request->get_param( 'orderby' );
240 $order = $request->get_param( 'order' );
241
242 $ordering_args = wc()->query->get_catalog_ordering_args( $orderby, $order );
243 $args['orderby'] = $ordering_args['orderby'];
244 $args['order'] = $ordering_args['order'];
245
246 if ( 'include' === $orderby ) {
247 $args['orderby'] = 'post__in';
248 } elseif ( 'id' === $orderby ) {
249 $args['orderby'] = 'ID'; // ID must be capitalized.
250 } elseif ( 'slug' === $orderby ) {
251 $args['orderby'] = 'name';
252 }
253
254 if ( $ordering_args['meta_key'] ) {
255 $args['meta_key'] = $ordering_args['meta_key']; // phpcs:ignore
256 }
257
258 // Filter by related products.
259 if ( ! empty( $request['related'] ) ) {
260 $product_id = absint( $request['related'] );
261 $related_product = wc_get_product( $product_id );
262
263 if ( ! $related_product || ! $related_product->is_visible() ) {
264 throw new RouteException(
265 'woocommerce_rest_product_not_found',
266 __( 'The related product ID is invalid or the product is not visible.', 'woocommerce' ), // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- REST API JSON response, not HTML.
267 404
268 );
269 }
270
271 $limit = ! empty( $request['per_page'] ) ? (int) $request['per_page'] : 100;
272 $related = wc_get_related_products( $product_id, $limit );
273
274 if ( ! empty( $related ) ) {
275 $args['post__in'] = ! empty( $args['post__in'] )
276 ? array_values( array_intersect( $args['post__in'], $related ) )
277 : array_values( $related );
278 } else {
279 // No related products found, return empty result.
280 $args['post__in'] = array( 0 );
281 }
282 }
283
284 return $args;
285 }
286
287 /**
288 * Convert the tax_query to a meta_query which is needed to support filtering by attributes for variations.
289 *
290 * @param array $tax_query The tax_query to convert.
291 * @return array
292 */
293 public function convert_tax_query_to_meta_query( $tax_query ) {
294 $meta_query = array();
295
296 foreach ( $tax_query as $tax_query_item ) {
297 $taxonomy = $tax_query_item['taxonomy'];
298 $terms = $tax_query_item['terms'];
299
300 $meta_key = 'attribute_' . $taxonomy;
301
302 $meta_query[] = array(
303 'key' => $meta_key,
304 'value' => $terms,
305 );
306
307 if ( isset( $tax_query_item['operator'] ) ) {
308 $meta_query[0]['compare'] = $tax_query_item['operator'];
309 }
310 }
311
312 return $meta_query;
313 }
314
315 /**
316 * Get results of query.
317 *
318 * @param \WP_REST_Request $request Request data.
319 * @return array
320 */
321 public function get_results( $request ) {
322 $query_args = $this->prepare_objects_query( $request );
323
324 add_filter( 'posts_clauses', array( $this, 'add_query_clauses' ), 10, 2 );
325
326 $query = new \WP_Query();
327 $results = $query->query( $query_args );
328 $total_posts = $query->found_posts;
329
330 // Out-of-bounds, run the query again without LIMIT for total count.
331 if ( $total_posts < 1 && $query_args['paged'] > 1 ) {
332 unset( $query_args['paged'] );
333 $count_query = new \WP_Query();
334 $count_query->query( $query_args );
335 $total_posts = $count_query->found_posts;
336 }
337
338 remove_filter( 'posts_clauses', array( $this, 'add_query_clauses' ), 10 );
339
340 return array(
341 'results' => $results,
342 'total' => (int) $total_posts,
343 'pages' => $query->query_vars['posts_per_page'] > 0 ? (int) ceil( $total_posts / (int) $query->query_vars['posts_per_page'] ) : 1,
344 );
345 }
346
347 /**
348 * Get objects.
349 *
350 * @param \WP_REST_Request $request Request data.
351 * @return array
352 */
353 public function get_objects( $request ) {
354 $results = $this->get_results( $request );
355
356 if ( ! empty( $results['results'] ) ) {
357 // Prime caches to reduce future queries.
358 _prime_post_caches( $results['results'] );
359 }
360
361 $objects = array_map( 'wc_get_product', $results['results'] );
362
363 // Batch-prime image attachment caches for the whole collection, rather than once per
364 // product when ProductSchema::get_images() runs during serialization.
365 wc_get_container()->get( ProductUtil::class )->prime_image_caches( $objects );
366
367 return array(
368 'objects' => $objects,
369 'total' => $results['total'],
370 'pages' => $results['pages'],
371 );
372 }
373
374 /**
375 * Get last modified date for all products as an HTTP-date (RFC 7232).
376 *
377 * The result is cached in the 'wc_products' object cache group and invalidated via the
378 * clean_post_cache hook in WC_Post_Data::invalidate_products_last_modified().
379 *
380 * Note: This intentionally does NOT use WordPress core's wp_cache_get_last_changed() /
381 * wp_cache_set_last_changed() pattern. Those functions are designed for opaque cache-key
382 * salting where auto-seeding with the current time on a cache miss is acceptable (a wrong
383 * salt simply causes a cache miss and re-query). Here, the value is exposed to clients via
384 * the Last-Modified HTTP header for collection cache invalidation. Auto-seeding with "now"
385 * on a cache miss would force all clients to unnecessarily invalidate their local caches.
386 * Instead, on a cache miss we fall back to the database to get the real last modification
387 * time and cache that.
388 *
389 * @return string|null HTTP-date formatted string, or null if no products exist.
390 */
391 public function get_last_modified() {
392 $last_modified = wp_cache_get( 'last_modified', 'wc_products' );
393
394 if ( false === $last_modified ) {
395 global $wpdb;
396
397 $last_modified_gmt = $wpdb->get_var(
398 "SELECT MAX( post_modified_gmt ) FROM {$wpdb->posts} WHERE post_type IN ( 'product', 'product_variation' )"
399 );
400
401 if ( ! $last_modified_gmt ) {
402 return null;
403 }
404
405 $last_modified = gmdate( 'D, d M Y H:i:s', strtotime( $last_modified_gmt ) ) . ' GMT';
406 wp_cache_set( 'last_modified', $last_modified, 'wc_products' );
407 }
408
409 return $last_modified;
410 }
411
412 /**
413 * Add in conditional search filters for products.
414 *
415 * @param array $args Query args.
416 * @param \WP_Query $wp_query WP_Query object.
417 * @return array
418 */
419 public function add_query_clauses( array $args, \WP_Query $wp_query ): array {
420 global $wpdb;
421
422 // SKU and slug lookups can return variations, so exclude any whose parent product is not published.
423 if ( in_array( 'product_variation', (array) $wp_query->get( 'post_type' ), true ) ) {
424 $args['where'] .= $wpdb->prepare(
425 " AND ( {$wpdb->posts}.post_type != 'product_variation' OR EXISTS (
426 SELECT 1 FROM {$wpdb->posts} AS parent
427 WHERE parent.ID = {$wpdb->posts}.post_parent AND parent.post_status = %s
428 ) ) ",
429 ProductStatus::PUBLISH
430 );
431 }
432
433 if ( $wp_query->get( 'search' ) ) {
434 $search = '%' . $wpdb->esc_like( $wp_query->get( 'search' ) ) . '%';
435 $search_query = wc_product_sku_enabled()
436 ? $wpdb->prepare( " AND ( $wpdb->posts.post_title LIKE %s OR wc_product_meta_lookup.sku LIKE %s ) ", $search, $search )
437 : $wpdb->prepare( " AND $wpdb->posts.post_title LIKE %s ", $search );
438 $args['where'] .= $search_query;
439 $args['join'] = $this->append_product_sorting_table_join( $args['join'] );
440 }
441
442 if ( $wp_query->get( 'sku' ) ) {
443 $skus = explode( ',', $wp_query->get( 'sku' ) );
444 // Include the current string as a SKU too.
445 if ( 1 < count( $skus ) ) {
446 $skus[] = $wp_query->get( 'sku' );
447 }
448 $args['join'] = $this->append_product_sorting_table_join( $args['join'] );
449 $args['where'] .= ' AND wc_product_meta_lookup.sku IN (\'' . implode( '\',\'', array_map( 'esc_sql', $skus ) ) . '\')';
450 }
451
452 if ( $wp_query->get( 'slug' ) ) {
453 $slugs = explode( ',', $wp_query->get( 'slug' ) );
454 // Include the current string as a slug too.
455 if ( 1 < count( $slugs ) ) {
456 $slugs[] = $wp_query->get( 'slug' );
457 }
458 $args['join'] = $this->append_product_sorting_table_join( $args['join'] );
459 $post_name__in = implode( '","', array_map( 'esc_sql', $slugs ) );
460 $args['where'] .= " AND $wpdb->posts.post_name IN (\"$post_name__in\")";
461 }
462
463 if ( $wp_query->get( 'stock_status' ) ) {
464 $args['join'] = $this->append_product_sorting_table_join( $args['join'] );
465 $args['where'] .= ' AND wc_product_meta_lookup.stock_status IN (\'' . implode( '\',\'', array_map( 'esc_sql', $wp_query->get( 'stock_status' ) ) ) . '\')';
466 } elseif ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
467 $args['join'] = $this->append_product_sorting_table_join( $args['join'] );
468 $args['where'] .= ' AND wc_product_meta_lookup.stock_status NOT IN (\'outofstock\')';
469 }
470
471 if ( $wp_query->get( 'min_price' ) || $wp_query->get( 'max_price' ) ) {
472 $args = $this->add_price_filter_clauses( $args, $wp_query );
473 }
474
475 return $args;
476 }
477
478 /**
479 * Add in conditional price filters.
480 *
481 * @param array $args Query args.
482 * @param \WC_Query $wp_query WC_Query object.
483 * @return array
484 */
485 protected function add_price_filter_clauses( $args, $wp_query ) {
486 global $wpdb;
487
488 $adjust_for_taxes = $this->adjust_price_filters_for_displayed_taxes();
489 $args['join'] = $this->append_product_sorting_table_join( $args['join'] );
490
491 if ( $wp_query->get( 'min_price' ) ) {
492 $min_price_filter = $this->prepare_price_filter( $wp_query->get( 'min_price' ) );
493
494 if ( $adjust_for_taxes ) {
495 $args['where'] .= $this->get_price_filter_query_for_displayed_taxes( $min_price_filter, 'max_price', '>=' );
496 } else {
497 $args['where'] .= $wpdb->prepare( ' AND wc_product_meta_lookup.max_price >= %f ', $min_price_filter );
498 }
499 }
500
501 if ( $wp_query->get( 'max_price' ) ) {
502 $max_price_filter = $this->prepare_price_filter( $wp_query->get( 'max_price' ) );
503
504 if ( $adjust_for_taxes ) {
505 $args['where'] .= $this->get_price_filter_query_for_displayed_taxes( $max_price_filter, 'min_price', '<=' );
506 } else {
507 $args['where'] .= $wpdb->prepare( ' AND wc_product_meta_lookup.min_price <= %f ', $max_price_filter );
508 }
509 }
510
511 return $args;
512 }
513
514 /**
515 * Get query for price filters when dealing with displayed taxes.
516 *
517 * @param float $price_filter Price filter to apply.
518 * @param string $column Price being filtered (min or max).
519 * @param string $operator Comparison operator for column.
520 * @return string Constructed query.
521 */
522 protected function get_price_filter_query_for_displayed_taxes( $price_filter, $column = 'min_price', $operator = '>=' ) {
523 global $wpdb;
524
525 // Select only used tax classes to avoid unwanted calculations.
526 $product_tax_classes = $wpdb->get_col( "SELECT DISTINCT tax_class FROM {$wpdb->wc_product_meta_lookup};" );
527
528 if ( empty( $product_tax_classes ) ) {
529 return '';
530 }
531
532 $or_queries = array();
533
534 // We need to adjust the filter for each possible tax class and combine the queries into one.
535 foreach ( $product_tax_classes as $tax_class ) {
536 $adjusted_price_filter = $this->adjust_price_filter_for_tax_class( $price_filter, $tax_class );
537 $or_queries[] = $wpdb->prepare(
538 '( wc_product_meta_lookup.tax_class = %s AND wc_product_meta_lookup.`' . esc_sql( $column ) . '` ' . esc_sql( $operator ) . ' %f )',
539 $tax_class,
540 $adjusted_price_filter
541 );
542 }
543
544 // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
545 return $wpdb->prepare(
546 ' AND (
547 wc_product_meta_lookup.tax_status = "taxable" AND ( 0=1 OR ' . implode( ' OR ', $or_queries ) . ')
548 OR ( wc_product_meta_lookup.tax_status != "taxable" AND wc_product_meta_lookup.`' . esc_sql( $column ) . '` ' . esc_sql( $operator ) . ' %f )
549 ) ',
550 $price_filter
551 );
552 // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
553 }
554
555 /**
556 * If price filters need adjustment to work with displayed taxes, this returns true.
557 *
558 * This logic is used when prices are stored in the database differently to how they are being displayed, with regards
559 * to taxes.
560 *
561 * @return boolean
562 */
563 protected function adjust_price_filters_for_displayed_taxes() {
564 $display = get_option( 'woocommerce_tax_display_shop' );
565 $database = wc_prices_include_tax() ? TaxDisplayMode::INCLUSIVE : TaxDisplayMode::EXCLUSIVE;
566
567 return $display !== $database;
568 }
569
570 /**
571 * Converts price filter from subunits to decimal.
572 *
573 * @param string|int $price_filter Raw price filter in subunit format.
574 * @return float Price filter in decimal format.
575 */
576 protected function prepare_price_filter( $price_filter ) {
577 return floatval( $price_filter / ( 10 ** wc_get_price_decimals() ) );
578 }
579
580 /**
581 * Adjusts a price filter based on a tax class and whether or not the amount includes or excludes taxes.
582 *
583 * This calculation logic is based on `wc_get_price_excluding_tax` and `wc_get_price_including_tax` in core.
584 *
585 * @param float $price_filter Price filter amount as entered.
586 * @param string $tax_class Tax class for adjustment.
587 * @return float
588 */
589 protected function adjust_price_filter_for_tax_class( $price_filter, $tax_class ) {
590 $tax_display = get_option( 'woocommerce_tax_display_shop' );
591 $tax_rates = WC_Tax::get_rates( $tax_class );
592 $base_tax_rates = WC_Tax::get_base_tax_rates( $tax_class );
593
594 // If prices are shown incl. tax, we want to remove the taxes from the filter amount to match prices stored excl. tax.
595 if ( TaxDisplayMode::INCLUSIVE === $tax_display ) {
596 /**
597 * Filters if taxes should be removed from locations outside the store base location.
598 *
599 * The woocommerce_adjust_non_base_location_prices filter can stop base taxes being taken off when dealing
600 * with out of base locations. e.g. If a product costs 10 including tax, all users will pay 10
601 * regardless of location and taxes.
602 *
603 * @since 2.6.0
604 *
605 * @internal Matches filter name in WooCommerce core.
606 *
607 * @param boolean $adjust_non_base_location_prices True by default.
608 * @return boolean
609 */
610 $taxes = apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ? WC_Tax::calc_tax( $price_filter, $base_tax_rates, true ) : WC_Tax::calc_tax( $price_filter, $tax_rates, true );
611 return $price_filter - array_sum( $taxes );
612 }
613
614 // If prices are shown excl. tax, add taxes to match the prices stored in the DB.
615 $taxes = WC_Tax::calc_tax( $price_filter, $tax_rates, false );
616
617 return $price_filter + array_sum( $taxes );
618 }
619
620 /**
621 * Join wc_product_meta_lookup to posts if not already joined.
622 *
623 * @param string $sql SQL join.
624 * @return string
625 */
626 protected function append_product_sorting_table_join( $sql ) {
627 global $wpdb;
628
629 if ( ! strstr( $sql, 'wc_product_meta_lookup' ) ) {
630 $sql .= " LEFT JOIN {$wpdb->wc_product_meta_lookup} wc_product_meta_lookup ON $wpdb->posts.ID = wc_product_meta_lookup.product_id ";
631 }
632 return $sql;
633 }
634 }
635