Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store API: Add support to query product_variations by attributes #42983

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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