WC_Comments::get_average_rating_for_product( WC_Product $product )
Get product rating for a product. Please note this is not cached.
Description Description
Parameters Parameters
- $product
-
(Required) Product instance.
Return Return
(float)
Source Source
File: includes/class-wc-comments.php
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;
}
Changelog Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |