Magento, Magento 2

How to Get Special Price of Product in Magento 2

How to Get Special Price of Product in Magento 2

In this tutorial, Today I will explain to how to get special price of product in Magento 2. In eCommerce website, Special price is useful when you want to promote your product and give discount to your customer by set special price. Special price will be display in catalog page and product details page.

Whenever, we develop any custom module related to Payment, Shipping, Order Related etc. at that time, we must need to check if special price will be set in that product we need to consider special price as price of that product instead of original price. So, Let’s follow the steps :

You may also like this :

Steps of How to Get Special Price of Product in Magento 2 :

1) First of all, Let’s assume that you have created simple module. I have added code in block file. You can add this below code in any file. You just need to inject \Magento\Catalog\Model\ProductRepository class in your construct


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $productRepository;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Model\ProductRepository         $productRepository
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    /**
     * Get Special Price By Product ID
     */
    public function getSpecialPriceByProId($proId)
    {
        $product = $this->productRepository->getById($proId);
        return $product->getSpecialPrice();
    }

    /**
     * Get Special Price By Product SKU
     */
    public function getSpecialPriceByProSku($proSku)
    {
        $product = $this->productRepository->get($proSku);
        return $product->getSpecialPrice();
    }
}

Using getSpecialPriceByProId($proId) function with pass product ID as Parameter you will get product special price by product id. If you want to get special price of product by product sku then, you need to call getSpecialPriceByProSku($proSku) function with pass product SKU as parameter.

That’s it !!!

Now, you just need to remove generated and clean cache.

I hope this blog is easy to understand about how to get special price of product in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged , ,