Magento, Get Ratings as a number in php

Magento, Get Ratings as a number in php

September 9, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento, Get Ratings as a number in php

Magento: Retrieving Product Ratings as a Number in PHP

As you’re working on implementing schema.org markup for your Magento storefront, you’ve run into a challenge when trying to display product ratings accurately using the getRatingSummary() function.

Understanding the Issue

The getRatingSummary() function returns a percentage of the total rating sum, not the actual numerical average rating from 0-5. This is why you’re seeing it used inside a CSS style attribute rather than as a standalone value.

Retrieving the Rating Sum and Count

Before we dive into calculating the average rating, let’s first understand how to get the raw data:

$reviews = $product->getRatingSummary();
$ratingSum = (int)$reviews['summary']['count'];
$ratingCount = (int)$reviews['summary']['rating_count'];

In this example, $ratingSum will contain the total rating sum for all reviews, and $ratingCount will hold the number of rated reviews.

Calculating the Average Rating

Now that we have the raw data, we can calculate the average rating:

$averageRating = ($ratingCount > 0) ? (int)($ratingSum / $ratingCount) : 0;

This snippet checks if there are any rated reviews ($ratingCount > 0). If so, it calculates the average by dividing the total sum by the count. If no reviews are available, it defaults to 0.

Updating Your Template

With the average rating calculated, you can now update your template accordingly:

<div class="ratings">
    <div class="rating-box">
        <span itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
            <div class="rating" style="width:<?php echo $averageRating * 20 ?>%">
                <meta itemprop="ratingValue" content="<?php echo $averageRating ?>" />
            </div>
            <span itemprop="reviewCount"><?php echo $ratingCount ?></span>
        </span>
    </div>
</div>

Notice that we’re now using <?php echo $averageRating * 20 ?>% for the width of the rating bar. This scales the average rating (which is now a number between 0 and 5) to a percentage value suitable for CSS styling.

Conclusion

By understanding how Magento handles product ratings and implementing our custom calculation, you can successfully integrate schema.org markup into your template while accurately displaying the numerical average rating.

Remember, it’s always important to verify your changes thoroughly after any core modifications. If you’re looking for more advanced development solutions or need expert guidance on your storefront optimization, feel free to reach out to us at LaravelCompany.com.

Happy coding!

Catalog Themes Errors

Our network