3

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.

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.