Site icon MageComp Blog

How to get a Special Price of the Product in Magento 2

How to get special price of the product in Magento 2

Magento 2 is one of featured pack CMS that comes with tons of preloaded configurations that makes it a perfect fit for any business. Even if you are setting up price for the product you can set 3 different kinds of prices including Group price, Special price & Tier price depending on your business needs. Several times it happens when the store owner is offering some of the store products at a discounted price for the specific period of time. During that specified time period, the special price appears instead of the regular price in the Magento 2 front, followed by a notation that shows the regular price.
Several times, it happens that while developing any payment related extension or functionality, the developer first needs to check that the product contains any special price or offered at a normal price before performing any pricing related operations. Because if any product contains a special price, then the base product price for the calculations will be special pricing, not the regular price. So, we are again back with a small piece of code that will help you to get the special price of the product in Magento 2.
Simply place below code anywhere in your extension or development to check that product contains special price or not.

Use below code to check if product have special price or not
$specialprice = $_product->getSpecialPrice();
$specialfromdate = $_product->getSpecialFromDate();
$specialtodate = $_product->getSpecialToDate();
$today = time();

   if ((is_null($specialfromdate) &&is_null($specialtodate)) || ($today >= 
    strtotime($specialfromdate) &&is_null($specialtodate)) || ($today <= 
    strtotime($specialtodate) &&is_null($specialfromdate)) || ($today >= 
    strtotime($specialfromdate) && $today <= strtotime($specialtodate))) {
    $specialPriceExist = true;
   }else{
     $specialPriceExist = false;
   }

then you can check like below in your code.

$specialPriceExist ? $specialPriceExist : $_product->getCustomUnitAmount()*$_product->getPricePerCustomUnit()

That’s it! If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.
And, Let us know if you are facing an issue while implementing this code.
Happy Coding!

Exit mobile version