WC_Comments::get_average_rating_for_product()public staticWC 3.0.0

Get product rating for a product. Please note this is not cached.

Method of the class: WC_Comments{}

No Hooks.

Return

float.

Usage

$result = WC_Comments::get_average_rating_for_product( $product );
$product(WC_Product) (required) (passed by reference — &)
Product instance.

Changelog

Since 3.0.0 Introduced.

WC_Comments::get_average_rating_for_product() code WC 8.7.0

public static function get_average_rating_for_product( &$product ) {
	global $wpdb;

	$count = $product->get_rating_count();

	if ( $count ) {
		$ratings = $wpdb->get_var(
			$wpdb->prepare(
				"
			SELECT SUM(meta_value) FROM $wpdb->commentmeta
			LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
			WHERE meta_key = 'rating'
			AND comment_post_ID = %d
			AND comment_approved = '1'
			AND meta_value > 0
				",
				$product->get_id()
			)
		);
		$average = number_format( $ratings / $count, 2, '.', '' );
	} else {
		$average = 0;
	}

	return $average;
}