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.


Top ↑

Return Return

(float)


Top ↑

Source Source

File: includes/class-wc-comments.php

319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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;
}

Top ↑

Changelog Changelog

Changelog
Version Description
3.0.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.