I want to show star ratings in a custom phtml file. The product object is available inside that phtml file. How can I achieve the rating star summery there?
Any suggestions please.
The below worked for me.
Below is the custom .phtml
file:
// Define your $_helper object here
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_reviewFactory = $_objectManager->create('Magento\Review\Model\Review');
$_storeId = $_helper->getCurrentStoreId(); //Store ID;
?>
<?php
// $_item is the product object
$_reviewFactory->getEntitySummary($_item, $_storeId);
$_ratingSummary = $_item->getRatingSummary()->getRatingSummary();
$_reviewCount = $_item->getRatingSummary()->getReviewsCount();
// var_dump($_item->getRatingSummary());
?>
<?php if ((int)$_ratingSummary > 0) : ?>
<div class="product-reviews-summary short">
<div class="rating-summary">
<span class="label"><span>Rating:</span></span>
<div title="<?php echo (int)$_ratingSummary; ?>%" class="rating-result">
<span style="width:<?php echo (int)$_ratingSummary; ?>%"><span><?php echo (int)$_ratingSummary; ?>
%</span></span>
</div>
</div>
<div class="reviews-actions">
<a href="#" class="action view">(<?php echo $_reviewCount; ?>)</a>
</div>
</div>
<?php endif; ?>
Now In your custom helper class write the below code to get current store id:
protected $_storeManager;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
parent::__construct($context);
$this->_storeManager = $storeManager;
}
public function getCurrentStoreId()
{
return $this->_storeManager->getStore()->getStoreId();
}
This will return you the exact star rating div as in Magento 2 Luma theme.