Automattic\WooCommerce\StoreApi\Utilities
ProductQuery::add_attribute_lookup_clauses
Apply attribute lookup filtering without depending on another query generator.
Keep lookup eligibility aligned with ProductFilters\QueryClauses.
Метод класса: ProductQuery{}
Хуков нет.
Возвращает
array. Updated clauses.
Использование
// private - только в коде основоного (родительского) класса $result = $this->add_attribute_lookup_clauses( $args, $attributes ): array;
- $args(массив) (обязательный)
- Product query clauses.
- $attributes(массив) (обязательный)
- Attribute taxonomy queries.
Код ProductQuery::add_attribute_lookup_clauses() ProductQuery::add attribute lookup clauses WC 11.3.0
private function add_attribute_lookup_clauses( array $args, array $attributes ): array {
global $wpdb;
$lookup_table = wc_get_container()->get( LookupDataStore::class )->get_lookup_table_name();
$in_stock_clause = 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) ? ' AND in_stock = 1' : '';
foreach ( $attributes as $attribute ) {
$term_field = 'term_id' === $attribute['field'] ? 'include' : 'slug';
$terms = get_terms(
array(
'taxonomy' => $attribute['taxonomy'],
'hide_empty' => false,
'fields' => 'ids',
$term_field => $attribute['terms'],
)
);
if ( ! is_array( $terms ) || ( 'AND' === $attribute['operator'] && count( $terms ) !== count( array_unique( (array) $attribute['terms'] ) ) ) ) {
$args['where'] .= ' AND 1=0';
continue;
}
if ( empty( $terms ) ) {
$args['where'] .= 'NOT IN' === $attribute['operator'] ? '' : ' AND 1=0';
continue;
}
$term_ids = implode( ',', wp_parse_id_list( $terms ) );
$count = count( $terms );
// Table names are internal; term IDs and counts are integers.
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
if ( 'AND' === $attribute['operator'] && $count > 1 ) {
$query = "
SELECT product_or_parent_id FROM {$lookup_table}
WHERE is_variation_attribute = 0 {$in_stock_clause} AND term_id IN ({$term_ids})
GROUP BY product_id HAVING COUNT(product_id) = {$count}
UNION
SELECT product_or_parent_id FROM {$lookup_table}
WHERE is_variation_attribute = 1 {$in_stock_clause} AND term_id IN ({$term_ids})
GROUP BY product_or_parent_id HAVING COUNT(DISTINCT term_id) = {$count}
";
} else {
$query = "SELECT product_or_parent_id FROM {$lookup_table} WHERE term_id IN ({$term_ids}) {$in_stock_clause}";
}
$operator = 'NOT IN' === $attribute['operator'] ? 'NOT IN' : 'IN';
// The derived table makes the filtering subquery execute once.
$args['where'] .= " AND {$wpdb->posts}.ID {$operator} ( SELECT product_or_parent_id FROM ({$query}) attribute_lookup )";
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
}
return $args;
}