5

I need to get the special price of a product by product Id or Sku. Let's say I have an existing product with Id '21' and Sku 'test-21'.

This information is provided in my custom block class, how can I get the special price of this product in mentioned custom class?

8

Use \Magento\Catalog\Model\ProductRepository class to get the special price of the product

protected $_productRepository;

public function __construct(
    ...      
    \Magento\Catalog\Model\ProductRepository $productRepository,
    ...
) {
    $this->_productRepository = $productRepository;
}

public function getSpecialPriceById($id)
{
    //$id = '21'; //Product ID
    $product = $this->_productRepository->getById($id);
    return $product->getSpecialPrice();
}

public function getSpecialPriceBySku($sku)
{   
    //$sku = 'test-21'; //Product Sku
    $product = $this->_productRepository->get($sku);
    return $product->getSpecialPrice();
}

Now you can get special price by

$id = '21';
$sku = 'test-21';
$this->getSpecialPriceById($id);
$this->getSpecialPriceBySku($sku);
  • How to get special price of configurable product? – Chirag Patel Jan 11 at 13:49
2

use Magento/Catalog/Model/ProductFactory to load product, and get price information from the model

Code is like:

$specialPrice = $this->productFactory()->create()->load($id)->getPriceInfo()->getPrice('special_price');

some reference about how to get product model in your custom module

use object manager: http://alanstorm.com/magento_2_object_manager_instance_objects/

use dependency injection: http://www.coolryan.com/magento/2016/01/27/dependency-injection-in-magento-2/

Normally dependency injection is recommended.

  • I am using Magento 2.1.7 and there is no class named ProductFactory under 'Magento/Catalog/Model/ProductFactory'. Can not find this class at '\vendor\magento\module-catalog\Model' – shahir hajir Sep 12 '17 at 20:49
  • Factory class are automatically created by magento, so if you have a model like /vendor/magento/module_catalog/Model/Product, then you can call ProductFactory directly without creating actual class file. – Tomi Sep 13 '17 at 2:12
  • $this->productFactory()->create() will return the model Magento/Catalog/Model/Product – Tomi Sep 13 '17 at 2:13
0

Here I am sharing the script to get the configurable product with special price.

magento2 SQL Query get special price for the configurable product with associated products:-

SELECT e.sku,e.type_id, d1.value as price, d2.value as special_price from catalog_product_entity e LEFT JOIN catalog_product_entity_decimal d1 ON e.entity_id = d1.entity_id
AND d1.store_id = 0
AND d1.attribute_id =75
LEFT JOIN catalog_product_entity_decimal d2 ON e.entity_id = d2.entity_id
AND d2.store_id = 0
AND d2.attribute_id =76

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.