How To Get Special Price Product Collection In Magento 2
The post shows the programmatic method to get special price product collection in Magento 2 store.
If you are an admin and is responsible to set the discounts and coupons for the store, this solution is going to be handy. Ever happened that you configured a special price for the products and after some time lost the track of it?
Also, it may happen that you need the list of all discounts offered in the Magento 2 store for the purpose of market study. You may want to find a change in customer behavior for purchase with respect to the special prices.
Additionally, studying special prices products is essential while calculating the profits! Manually listing the products with special prices is a tedious task and prone to human error.
To avoid it, implement the below code to get a special price product collection in Magento 2. If you do not want the collection but simply check if the product has a special price in Magento 2, refer to the earlier posted solution.
Method To Get Special Price Product Collection In Magento 2:
Create SpecialPrice.php in app/code/[Vendor]/[Module]/Block Folder add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<?php namespace [Vendor]\[Module]\Block; use Magento\Catalog\Api\CategoryRepositoryInterface; use Magento\Catalog\Block\Product\Context; use Magento\Catalog\Block\Product\ListProduct; use Magento\Framework\Data\Helper\PostHelper; use Magento\Framework\Url\Helper\Data; use Magento\Catalog\Model\ResourceModel\Product\Collection; use Magento\Framework\App\ResourceConnection; class SpecialPrice extends ListProduct { protected $collection; protected $categoryRepository; protected $resource; public function __construct(Context $context, PostHelper $postDataHelper, Resolver $layerResolver, CategoryRepositoryInterface $categoryRepository, Data $urlHelper, Collection $collection, ResourceConnection $resource, array $data = []) { $this->categoryRepository = $categoryRepository; $this->collection = $collection; $this->resource = $resource; parent::__construct($context, $postDataHelper, $layerResolver, $categoryRepository, $urlHelper, $data); } public function getProducts() { $count = $this->getProductCount(); $category_id = $this->getData("category_id"); $collection = clone $this->collection; $collection ->clear() ->getSelect() ->reset(\Magento\Framework\DB\Select::WHERE)->reset(\Magento\Framework\DB\Select::ORDER) ->reset(\Magento\Framework\DB\Select::LIMIT_COUNT) ->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET) ->reset(\Magento\Framework\DB\Select::GROUP); if (!$category_id) { $category_id = $this->_storeManager->getStore()->getRootCategoryId(); } $category = $this->categoryRepository->get($category_id); $now = date('Y-m-d'); if (isset($category) && $category) { $collection->addMinimalPrice() ->addFinalPrice() ->addTaxPercents()->addAttributeToSelect('name') ->addAttributeToSelect('image')->addAttributeToSelect('small_image') ->addAttributeToSelect('thumbnail')->addAttributeToSelect('special_from_date') ->addAttributeToSelect('special_to_date')->addAttributeToFilter('special_price', ['neq' => '']) ->addAttributeToFilter([['attribute' => 'special_from_date', 'lteq' => date('Y-m-d G:i:s', strtotime($now)), 'date' => true, ], ['attribute' => 'special_to_date', 'gteq' => date('Y-m-d G:i:s', strtotime($now)), 'date' => true,]]) ->addAttributeToFilter('is_saleable', 1, 'left'); } else { $collection->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addAttributeToSelect('name') ->addAttributeToSelect('image') ->addAttributeToSelect('small_image') ->addAttributeToSelect('thumbnail') ->addAttributeToFilter('special_price', ['neq' => '']) ->addAttributeToSelect('special_from_date') ->addAttributeToSelect('special_to_date') ->addAttributeToFilter([['attribute' => 'special_from_date', 'lteq' => date('Y-m-d G:i:s', strtotime($now)), 'date' => true, ], ['attribute' => 'special_to_date', 'gteq' => date('Y-m-d G:i:s', strtotime($now)), 'date' => true,]]) ->addAttributeToFilter('is_saleable', 1, 'left'); } $collection->getSelect() ->limit($count); return $collection; } public function getLoadedProductCollection() { return $this->getProducts(); } public function getProductCount() { $limit = $this->getData("product_count"); if (!$limit) $limit = 10; return $limit; } } |
Use Block as per your requirement in product listing page
That’s it.
Any doubts about the topic or the implementation of the code? Please feel free to mention them in the Comments section below and I’d be happy to help you out asap.
The solution was helpful to you? Do share the same with fellow Magento developers via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
4 Comments
Hi, Is it with filter option.
Hello Prabharan,
It is filter with special price option.
Thank you.
Hi, I’m getting an error like this after trying to use this new block
Exception #0 (Magento\Framework\Exception\LocalizedException): Invalid block type: [Vendor]\[Module]\Block\SpecialPrice
Exception #1 (ReflectionException): Class [Vendor]\[Module]\Block\SpecialPrice\Interceptor does not exist
P.S. Of course I replaced [Vendor] & [Module] with real name folders.
Can you help me please?
How have you called the block in the module you have created?