Skip to content

Commit

Permalink
Store API: Add support to query product_variations by attributes (#42983
Browse files Browse the repository at this point in the history
)

Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Paulo Arromba <17236129+wavvves@users.noreply.github.com>
  • Loading branch information
3 people committed Dec 21, 2023
1 parent 99fc85a commit a9550d8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: fix

Store API: Add support to query `product_variations` by attribute slugs.
37 changes: 36 additions & 1 deletion plugins/woocommerce/src/StoreApi/Utilities/ProductQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,19 @@ function ( $value ) {
}

// Build tax_query if taxonomies are set.
if ( ! empty( $tax_query ) ) {
if ( ! empty( $tax_query ) && 'product_variation' !== $args['post_type'] ) {
if ( ! empty( $args['tax_query'] ) ) {
$args['tax_query'] = array_merge( $tax_query, $args['tax_query'] ); // phpcs:ignore
} else {
$args['tax_query'] = $tax_query; // phpcs:ignore
}
} else {
// For product_variantions we need to convert the tax_query to a meta_query.
if ( ! empty( $args['tax_query'] ) ) {
$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
} else {
$args['meta_query'] = $this->convert_tax_query_to_meta_query( $tax_query ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
}
}

// Filter featured.
Expand Down Expand Up @@ -239,6 +246,34 @@ function ( $value ) {
return $args;
}

/**
* Convert the tax_query to a meta_query which is needed to support filtering by attributes for variations.
*
* @param array $tax_query The tax_query to convert.
* @return array
*/
public function convert_tax_query_to_meta_query( $tax_query ) {
$meta_query = array();

foreach ( $tax_query as $tax_query_item ) {
$taxonomy = $tax_query_item['taxonomy'];
$terms = $tax_query_item['terms'];

$meta_key = 'attribute_' . $taxonomy;

$meta_query[] = array(
'key' => $meta_key,
'value' => $terms,
);

if ( isset( $tax_query_item['operator'] ) ) {
$meta_query[0]['compare'] = $tax_query_item['operator'];
}
}

return $meta_query;
}

/**
* Get results of query.
*
Expand Down

0 comments on commit a9550d8

Please sign in to comment.