Skip to content

Commit 056720d

Browse files
committed
Search within current terms to reduce meta query
Closes woocommerce#16591
1 parent 671a4d7 commit 056720d

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

includes/class-wc-query.php

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -514,9 +514,27 @@ public function order_by_price_asc_post_clauses( $args ) {
514514
* @return array
515515
*/
516516
public function order_by_price_desc_post_clauses( $args ) {
517-
global $wpdb;
518-
$args['join'] .= " INNER JOIN ( SELECT post_id, max( meta_value+0 ) price FROM $wpdb->postmeta WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
517+
global $wpdb, $wp_query;
518+
519+
if ( isset( $wp_query->queried_object, $wp_query->queried_object->term_taxonomy_id, $wp_query->queried_object->taxonomy ) && is_a( $wp_query->queried_object, 'WP_Term' ) ) {
520+
$search_within_terms = get_term_children( $wp_query->queried_object->term_taxonomy_id, $wp_query->queried_object->taxonomy );
521+
$search_within_terms[] = $wp_query->queried_object->term_taxonomy_id;
522+
$args['join'] .= " INNER JOIN (
523+
SELECT post_id, max( meta_value+0 ) price
524+
FROM $wpdb->postmeta
525+
INNER JOIN (
526+
SELECT $wpdb->term_relationships.object_id
527+
FROM $wpdb->term_relationships
528+
WHERE 1=1
529+
AND $wpdb->term_relationships.term_taxonomy_id IN (" . implode( ',', array_map( 'absint', $search_within_terms ) ) . ")
530+
) as products_within_terms ON $wpdb->postmeta.post_id = products_within_terms.object_id
531+
WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
532+
} else {
533+
$args['join'] .= " INNER JOIN ( SELECT post_id, max( meta_value+0 ) price FROM $wpdb->postmeta WHERE meta_key='_price' GROUP BY post_id ) as price_query ON $wpdb->posts.ID = price_query.post_id ";
534+
}
535+
519536
$args['orderby'] = " price_query.price DESC ";
537+
520538
return $args;
521539
}
522540

0 commit comments

Comments
 (0)