Automattic\WooCommerce\Blocks
QueryFilters::get_attribute_counts
Get attribute counts for the current products.
Method of the class: QueryFilters{}
No Hooks.
Returns
Array. termId=>count pairs.
Usage
$QueryFilters = new QueryFilters(); $QueryFilters->get_attribute_counts( $query_vars, $attribute_to_count );
- $query_vars(array) (required)
- The WP_Query arguments.
- $attribute_to_count(string) (required)
- Attribute taxonomy name.
QueryFilters::get_attribute_counts() QueryFilters::get attribute counts code WC 10.7.0
public function get_attribute_counts( $query_vars, $attribute_to_count ) {
global $wpdb;
add_filter( 'posts_clauses', array( $this, 'add_query_clauses' ), 10, 2 );
add_filter( 'posts_pre_query', '__return_empty_array' );
$query_vars['no_found_rows'] = true;
$query_vars['posts_per_page'] = -1;
$query_vars['fields'] = 'ids';
$query = new \WP_Query();
$result = $query->query( $query_vars );
$product_query_sql = $query->request;
remove_filter( 'posts_clauses', array( $this, 'add_query_clauses' ), 10 );
remove_filter( 'posts_pre_query', '__return_empty_array' );
$attributes_to_count = esc_sql( wc_sanitize_taxonomy_name( $attribute_to_count ) );
$attribute_count_sql = "SELECT COUNT(DISTINCT posts.ID) as term_count, terms.term_id as term_count_id
FROM {$wpdb->posts} AS posts
INNER JOIN {$wpdb->term_relationships} AS term_relationships ON posts.ID = term_relationships.object_id
INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
INNER JOIN {$wpdb->terms} AS terms ON term_taxonomy.term_id = terms.term_id
WHERE posts.ID IN ( {$product_query_sql} )
AND term_taxonomy.taxonomy IN ('{$attributes_to_count}')
AND posts.post_status = 'publish'
AND posts.post_type = 'product'
GROUP BY terms.term_id
ORDER BY terms.name ASC";
$results = $wpdb->get_results( $attribute_count_sql ); // phpcs:ignore
return array_map( 'absint', wp_list_pluck( $results, 'term_count', 'term_count_id' ) );
}