Automattic\WooCommerce\Internal\ProductFilters
QueryClauses::add_attribute_taxonomy_clauses
Add attribute clauses using WordPress taxonomy queries.
Method of the class: QueryClauses{}
No Hooks.
Returns
array.
Usage
// private - for code of main (parent) class only $result = $this->add_attribute_taxonomy_clauses( $args, $chosen_attributes ): array;
- $args(array) (required)
- Query args.
- $chosen_attributes(array) (required)
- Chosen attributes.
QueryClauses::add_attribute_taxonomy_clauses() QueryClauses::add attribute taxonomy clauses code WC 11.3.0
private function add_attribute_taxonomy_clauses( array $args, array $chosen_attributes ): array {
global $wpdb;
$all_term_slugs = array();
foreach ( $chosen_attributes as $data ) {
if ( ! empty( $data['terms'] ) && is_array( $data['terms'] ) ) {
$all_term_slugs = array_merge( $all_term_slugs, $data['terms'] );
}
}
if ( empty( $all_term_slugs ) ) {
$args['where'] .= ' AND 1=0';
return $args;
}
$all_terms = get_terms(
array(
'taxonomy' => array_keys( $chosen_attributes ),
'slug' => $all_term_slugs,
'hide_empty' => false,
)
);
if ( is_wp_error( $all_terms ) ) {
$args['where'] .= ' AND 1=0';
return $args;
}
$term_ids_by_taxonomy = array();
foreach ( $all_terms as $term ) {
$term_ids_by_taxonomy[ $term->taxonomy ][ $term->slug ] = (int) $term->term_id;
}
$clauses = array();
foreach ( $chosen_attributes as $taxonomy => $data ) {
$term_ids = array_values( array_intersect_key( $term_ids_by_taxonomy[ $taxonomy ] ?? array(), array_flip( $data['terms'] ) ) );
$is_and = 'and' === strtolower( $data['query_type'] );
$unique_terms = array_unique( $data['terms'] );
if ( empty( $term_ids ) || ( $is_and && count( $term_ids ) !== count( $unique_terms ) ) ) {
$args['where'] .= ' AND 1=0';
return $args;
}
$term_ids_list = '(' . implode( ',', array_map( 'absint', $term_ids ) ) . ')';
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
if ( $is_and && count( $term_ids ) > 1 ) {
$clauses[] = $wpdb->prepare(
"{$wpdb->posts}.ID IN (
SELECT tr.object_id FROM {$wpdb->term_relationships} tr
INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.taxonomy = %s
AND tt.term_id IN {$term_ids_list}
GROUP BY tr.object_id
HAVING COUNT(DISTINCT tt.term_id) = %d
)",
$taxonomy,
count( $term_ids )
);
} else {
$clauses[] = $wpdb->prepare(
"EXISTS (
SELECT 1 FROM {$wpdb->term_relationships} tr
INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE tr.object_id = {$wpdb->posts}.ID
AND tt.taxonomy = %s
AND tt.term_id IN {$term_ids_list}
)",
$taxonomy
);
}
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
}
$args['where'] .= ' AND (' . implode( ' AND ', $clauses ) . ')';
return $args;
}