cancel
Showing results for 
Search instead for 
Did you mean: 

How to get the percentage of reviews of each product by product id in Magento 2?

How to get the percentage of reviews of each product by product id in Magento 2?

For example, I have 5 5-star reviews, 3 2-star reviews and 2 1-star reviews, when var_dump on the screen, it will look like this: 50% 5-star reviews, 30% 2-star reviews, 20% 1-star reviews Pls help me, thanks

2 REPLIES 2

Re: How to get the percentage of reviews of each product by product id in Magento 2?

@azizusman88105 

Use the below code to get the percentage of reviews for each product by product id in Magento 2:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product_id = 10;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

$reviewFactory = $objectManager->create('Magento\Review\Model\Review');
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getStoreId();
$reviewFactory->getEntitySummary($product, $storeId);
$ratingSummary = $product->getRatingSummary()->getRatingSummary();
$rat = (int)$ratingSummary;

echo $rat;
Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.

Re: How to get the percentage of reviews of each product by product id in Magento 2?

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product_id = 1;
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
$review = $objectManager->create('Magento\Review\Model\Review');
$store = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$storeId = $store->getStore()->getStoreId();
$review->getEntitySummary($product, $storeId);
$ratingSummary = $product->getRatingSummary()->getRatingSummary();
$rating = (int)$ratingSummary;
echo $rating;