Magento Tutorials

How to Get Special Price Product Collection In Magento 2

Hello Magento Folks,

In this article, I will help you to learn How To Get Special Price Product Collection In Magento 2. Also, check out our latest post where I have illustrated How to add Custom Tab in Customer Account in Magento 2. 

Many times when the store admin sets discounts for their Magento 2 store if you are that person then this article is very helpful for you. Basically, when the special price is configured after that there is difficulty in tracking those products. Sometimes the admin will require this data for analyzing the market and finding the change in the behavior of customers when a special price is offered. When this task is performed manually then there will be a waste of time and it will be a difficult task. There are also chances of mistakes therefore ignore all these tactics and apply the below-given steps to Get Special Price Product Collection In Magento 2.

Steps to Get Special Price Product Collection In Magento 2:

Step 1: Firstly, Create a routes.xml file at the given below path and add code to it.

app\code\Vendor\Extension\etc\frontend\

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="routesname" id="routesname">
            <module name="Vendor_Extension"/>
        </route>
    </router>
</config>

Step 2: Create routesname_product_index.xml file at the given below path and add code to it.

app\code\Vendor\Extension\view\frontend\layout\

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Extension\Block\Getproductspecialprice" name="custom_tab" template="Vendor_Extension::specialpricedata.phtml" />
        </referenceContainer>
    </body>
</page>

Step 3: Create Index.php file at the given below path and add code to it.

app\code\Vendor\Extension\Controller\product\

<?php
namespace Vendor\Extension\Controller\Customer;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory)
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        return $this->_pageFactory->create();
    }
}

Step 4: Create the Getproductspecialprice.php file at the given below path and add code to it.

app\code\Vendor\Extension\Block\

<?php
namespace Vendor\Extension\Block;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Block\Product\Context;
use Magento\Framework\Data\Helper\PostHelper;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Framework\Url\Helper\Data;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Framework\App\ResourceConnection;
class Getproductspecialprice extends \Magento\Catalog\Block\Product\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 getproductcollection()
    {
        $count = 10;
        $category_id = $this->getData("category_id"); // pass your 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();
        }
        $categorycollection = $this->categoryRepository->get($category_id);
        $today_date = date('Y-m-d');
        if (isset($categorycollection) && $categorycollection)
        {
            $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($today_date)),
                        'date' => true,
                    ],
                    [
                        'attribute' => 'special_to_date',
                        'gteq' => date('Y-m-d G:i:s', strtotime($today_date)),
                        '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($today_date)),
                        'date' => true,
                    ],
                    [
                        'attribute' => 'special_to_date',
                        'gteq' => date('Y-m-d G:i:s', strtotime($today_date)),
                        'date' => true,
                    ]
                ])
                ->addAttributeToFilter('is_saleable', 1, 'left');
        }
        $collection->getSelect()->limit($count);
        return $collection;
    }
}

Step 5: Create a specialpricedata.phtml file at the given below path add code to it.

app\code\Vendor\Extension\view\frontend\templates

<?php foreach ($block->getproductcollection() as $product)
{
    echo '<pre>';
    //print_r($product->getSpecialPrice());  // this code for getSpecialPrice for products
    print_r($product->getData());   // this line get all getSpecialPrice products collection
    echo '</pre>';
}

Wrap Up:

Hopefully, all are able to Get Special Price Product Collection In Magento 2 by implementing the above-given steps. If you find any difficulties in following the above steps then connect with me in the comment section below. You can also take the help of our Certified Magento developers to help you in getting a special price product collection in Magento 2.

Share the article with your Magento Store Admin friends.

Happy Reading.

Click to rate this post!
[Total: 11 Average: 3.9]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago