Automattic\WooCommerce\Blocks

QueryFilters::get_attribute_counts()publicWC 1.0

Get attribute counts for the current products.

Method of the class: QueryFilters{}

No Hooks.

Return

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() code WC 8.9.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_sql = 'AND term_taxonomy.taxonomy IN ("' . 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 USING( term_taxonomy_id )
		INNER JOIN {$wpdb->terms} AS terms USING( term_id )
		WHERE posts.ID IN ( {$product_query_sql} )
		{$attributes_to_count_sql}
		GROUP BY terms.term_id
	";

	$results = $wpdb->get_results( $attribute_count_sql ); // phpcs:ignore

	return array_map( 'absint', wp_list_pluck( $results, 'term_count', 'term_count_id' ) );
}