How to display product discount percent on product details page and category page in Magento 2.

To show discount % on product detail page add below code where you want. This will show discount % either applied with Catalog Price rule or added Special price.
For example to show % near stock status add code in below template : Theme/Magento_Catalog/templates/product/view/type/default.phtml.
<?php
$simplePrice = 0;
$_savingPercent = 0;
if($_product->getTypeId() == "simple") {
   $simplePrice = $_product->getPrice();
} else {
   $_children = $_product->getTypeInstance()->getUsedProducts($_product);
    foreach ($_children as $child){
    $simplePrice = $child->getPrice();
    break;
   }
}

$_finalPrice =$_product->getFinalPrice();
$_price = $simplePrice;
if($_finalPrice < $_price) {
   $_savingPercent = 100 - round(($_finalPrice / $_price)*100);
   echo 'Your save '.$_savingPercent . '%';

}
?>
Same code will use for category page also.
Thanks!

Comments