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: 9 Average: 4.1]
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

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

2 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

5 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

5 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

5 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

6 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago