Magento – Magento2 : Display percentage of discount on product list and view page

discountmagento2pricesale-price

I want to display discount in percentage format on product list and product view page as like below

30% Discount

How I can achieve this task in proper Magento-2 way.

Code should be define in any one place and use it in anywhere.

thanks in advance.

Best Answer

Try this in design/frontend/Vendor_Name/Theme_Name/Magento_Catalog/templates/product/list.phtml

<?php
    $specialprice = $_product->getSpecialPrice();
    $specialPriceFromDate = $_product->getSpecialFromDate();
    $specialPriceToDate = $_product->getSpecialToDate();    
    $today = time();
    $price = $_product->getPrice();
    if($price){
        $sale = round((($price-$specialprice)/$price)*100);
    }
    if ($specialprice) {
        if ($today >= strtotime($specialPriceFromDate) && $today <= strtotime($specialPriceToDate) || $today >= strtotime($specialPriceFromDate) && is_null($specialPriceToDate)) { ?>
            <div class="label-product label-sale">
                <span class="sale-product-icon">
                    <?php if($sale) { echo $sale.'%'; } else {echo __('Sale');} ?>
                </span>
            </div>
        <?php }
    }
?>

The same way you can do it from product page.

Related Topic