Today's tutorial will help you with a step by step tutorial to help you get the special price of products in Magento 2. On an ecommerce website, the special price is useful when you are promoting any particular product and you want to offer discounts to the customers by a set special price. Special prices can be displayed on the catalog page as well as the product details page.
Also read: How to Configure Minimum Advertised Price in Magento 2?
How to Get Special Price of Product in Magento 2?
Step 1.
First of all, Let’s assume that a simple module is already created. We have added the code in a block file, this below code can be added in any file.
Step 2.
All you need to is inject \Magento\Catalog\Model\ProductRepository class in your construct.
<?php namespace MD\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(); } }
Step 3.
Using getSpecialPriceByProId($proId) function with pass product ID as Parameter, you can get the product's special price by product id. If you are looking to a get special price of the product by product SKU, you'll require to call getSpecialPriceByProSku($proSku) function with pass product SKU as a parameter.
Here you go!
We believe that we have covered every step to get a special price on the Magento 2 store. If we missed out on anything, contact us today!
Recommended: Magento 2 Advanced Promotions to offer next-level deals, discounts & offers to customers
Also read: How to Get Formatted Price with Currency in Magento 2?