Automattic\WooCommerce\Blocks

QueryFilters::get_rating_counts()publicWC 1.0

Get rating counts for the current products.

Method of the class: QueryFilters{}

No Hooks.

Return

Array. rating=>count pairs.

Usage

$QueryFilters = new QueryFilters();
$QueryFilters->get_rating_counts( $query_vars );
$query_vars(array) (required)
The WP_Query arguments.

QueryFilters::get_rating_counts() code WC 9.0.1

public function get_rating_counts( $query_vars ) {
	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();
	$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' );

	$rating_count_sql = "
		SELECT COUNT( DISTINCT product_id ) as product_count, ROUND( average_rating, 0 ) as rounded_average_rating
		FROM {$wpdb->wc_product_meta_lookup}
		WHERE product_id IN ( {$product_query_sql} )
		AND average_rating > 0
		GROUP BY rounded_average_rating
		ORDER BY rounded_average_rating ASC
	";

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

	return array_map( 'absint', wp_list_pluck( $results, 'product_count', 'rounded_average_rating' ) );
}