Display Total Customers Reviews and Ratings Average in Woocommerce

Display total customers reviews and ratings average in WooCommerce

Update (Avoiding an error on the last function when there is no reviews yet)

Below you will find 4 custom functions that will give you:

  1. The total products reviews count
  2. The products ratings count data, that will be used in:

    • The products count by rating output html
    • The products rating average output html

THE FUNCTIONS CODE:

function get_total_reviews_count(){
return get_comments(array(
'status' => 'approve',
'post_status' => 'publish',
'post_type' => 'product',
'count' => true
));
}

function get_products_ratings(){
global $wpdb;

return $wpdb->get_results("
SELECT t.slug, tt.count
FROM {$wpdb->prefix}terms as t
JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_id = t.term_id
WHERE t.slug LIKE 'rated-%' AND tt.taxonomy LIKE 'product_visibility'
ORDER BY t.slug
");
}

function products_count_by_rating_html(){
$star = 1;
$html = '';
foreach( get_products_ratings() as $values ){
$star_text = '<strong>'.$star.' '._n('Star', 'Stars', $star, 'woocommerce').'<strong>: ';
$html .= '<li class="'.$values->slug.'">'.$star_text.$values->count.'</li>';
$star++;
}
return '<ul class="products-rating">'.$html.'</ul>';
}

function products_rating_average_html(){
$stars = 1;
$average = 0;
$total_count = 0;
if( sizeof(get_products_ratings()) > 0 ) :
foreach( get_products_ratings() as $values ){
$average += $stars * $values->count;
$total_count += $values->count;
$stars++;
}
return '<p class="rating-average">'.round($average / $total_count, 1).' / 5 '. __('Stars average').'</p>';
else :
return '<p class="rating-average">'. __('No reviews yet', 'woocommerce').'</p>';
endif;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

USAGE

  1. Total customers reviews:

    echo '<p>'.__('Total reviews','woocommerce').': '.get_total_reviews_count().'</p>';
  2. The products count by ratings list:

    echo products_count_by_rating_html();
  3. The products rating average:

    echo products_rating_average_html();

Get product reviews average rating in a custom WooCommerce repport

Have a look to this answer thread, where you'll see that you can use WC_Product methods like:

  • get_average_rating()
  • get_rating_counts()

Here is a complete example:

1) Get the products required related data (customizable):

$products_data = []; // Initializing

$products = wc_get_products( ['limit' => -1] ); // Get all WC_Product objects

// Loop through products -- Preparing data to be displayed
foreach ( $products as $product ) {
$product_id = $product->get_id();

// 1. Product data as product name …
$products_data[$product_id]['name'] = $product->get_name();

// 2. Average rating and rating count
$products_data[$product_id]['rating'] = (float) $product->get_average_rating();
$products_data[$product_id]['count'] = (int) $product->get_rating_count();

// 3. Reviews -- Loop though product reviews
foreach( get_approved_comments( $product_id ) as $review ) {
if( $review->comment_type === 'review' ) {
$products_data[$product_id]['reviews'][] = (object) [
'author' => $review->comment_author,
'email' => $review->comment_author_email,
'date' => strtotime($review->comment_date),
'content' => $review->comment_content,
];
}
}
}

2) Customizable display in a table:

echo '<table class="products-reviews-ratings"><tr>
<th>'.__("ID").'</th>
<th>'.__("Name").'</th>
<th>'.__("Rating").'</th>
<th>'.__("count").'</th>
<th style="text-align:center">'.__("Reviews (author, date and content)").'</th>
</tr>';

foreach ($products_data as $product_id => $data){
echo '<tr>
<td>'.$product_id.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['rating'].'</td>
<td>'.$data['count'].'</td>
<td style="text-align:center">';

if( isset($data['reviews']) && $data['reviews'] > 0 ) {
echo '<table>';

// Loop through reviews
foreach ($data['reviews'] as $review ){
echo '<tr>
<td><a href="mailto:'.$review->email.'">'.$review->author.'</a></td>
<td>'.date( 'Y-m-d', $review->date ).'</td>
<td>'.$review->content.'</td>
</tr>';
}
echo '</table>';
} else {
_e('No reviews yet');
}

echo '</td></tr>';
}
echo '</table>';

You will get something like:

Sample Image

Add stars rating and average to product Review item menu in Woocommerce

Update 2: The following code will display something like "4.5/5 (5 reviews)" below the review item menu title and stars in Woocommerce single product pages tabs:

add_filter( 'woocommerce_product_reviews_tab_title', 'add_stars_to_review_tab', 98 );
function add_stars_to_review_tab( $title ) {
global $product;

$average_rating = $product->get_average_rating();
$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();

if( ! empty($average_rating) && $average_rating > 0 ) {
return '<div>' . $title . '</div>' . wc_get_rating_html($average_rating) . sprintf(
'<div class="stars">%s / 5 (%s %s)</div>',
$average_rating,
$review_count,
_n( "review", "reviews", $review_count, "woocommerce" )
);
}
return $title;
}

Code goes in function.php file of your active child theme (active theme). Tested and works.

Sample Image

Avoid a NAN result error when displaying ratings average in Woocommerce

Use an if and check to see if $total_count === 0:

function products_rating_average_html(){
$stars = 1;
$average = 0;
$total_count = 0;
foreach( get_products_ratings() as $values ){
$average += $stars * $values->count;
$total_count += $values->count;
$stars++;
}

if ($total_count === 0) {
return 'No Reviews';
}

return '<p class="rating-average"><b>'.round($average / $total_count, 1).' / 5 </b>'. __('Rating Stars Average').'</p>';
}

How to display reviews on an under product title in cart of woocommerce?

You can use the woocommerce_after_cart_item_name action hook to display reviews below the title. code will go in your active theme functions.php file.

add_filter('woocommerce_after_cart_item_name', 'woocommerce_after_cart_item_name', 10, 2);
function woocommerce_after_cart_item_name( $cart_item, $cart_item_key ){
$product = wc_get_product( $cart_item['product_id'] );
$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();
$average = $product->get_average_rating();
if ( $rating_count > 0 ) : ?>
<div class="woocommerce-product-rating">
<?php echo wc_get_rating_html( $average, $rating_count ); // WPCS: XSS ok. ?>
<div class="count"><?php echo esc_html( $review_count ); ?> Reviews</div>
</div>
<?php endif;
}

Tested and Works

Sample Image

Display woocommerce review count next to star rating

Woocommerce already displays reviews count next to star rating in single product page. But on shop and archives page it displays only star rating. Follow the below steps to display star rating count even on shop and archives pages.

Step 1) Create a new folder in your theme’s root and name it ‘woocommerce’

Step 2) Create a new folder in the newly created ‘woocommerce’ folder and name it ‘loop’

Step 3) Add ‘rating.php’ file to the newly created ‘loop’ folder

Now your directory would look something like this

/public_html/wp-content/themes/YOUR-THEME/woocommerce/loop

Add the below code to the newly created ‘rating.php’ and customize it according to your need.

<?php
/**
* Loop Rating
*
* This template can be overridden by copying it to yourtheme/woocommerce/loop/rating.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 3.0.0
*/

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

global $product;

if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' ) {
return;
}

$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();
$average = $product->get_average_rating();

if ( $rating_count >= 0 ) : ?>

<?php echo wc_get_rating_html($average, $rating_count); ?>
<?php if ( comments_open() ): ?><a href="<?php echo get_permalink() ?>#reviews" class="woocommerce-review-link" rel="nofollow">(<?php printf( _n( '%s',$review_count,'woocommerce' ), '<span class="count">' . esc_html( $review_count ) . '</span>' ); ?>)</a><?php endif ?>

<?php endif; ?>

In case this doesn’t work

Add ‘templates’ folder in ‘woocommerce’ folder and then add ‘loop’ folder in ‘templates’ folder.

Now the directory would look like this

/public_html/wp-content/themes/YOUR-THEME/woocommerce/templates/loop

How to display a message instead of star rating for products with no reviews

This should suffice as an extra check

function add_star_rating() {
// Check if reviews ratings are enabled - WooCommerce Settings
if ( ! wc_review_ratings_enabled() ) {
return;
}

if( !is_front_page() ) {
global $product;

// Get average
$average = $product->get_average_rating();

// Average > 0
if ($average > 0) {
echo '<div class="star-rating"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'out of 5', 'woocommerce' ).'</span></div>';
} else {
echo '<div>No reviews yet</div>';
}
}
}
add_action('woocommerce_shop_loop_item_title', 'add_star_rating', 10 );


Related Topics



Leave a reply



Submit