Price range filter in Magento 2

create category custom layout in Magento 2

Today we disscus about price range filter in Magento 2, Sometime we need product collection filter by min_price, final_price and minimal_price range in custom module.

There are some below solutions.

Solution 1

The final_price is part of the price index tables, so you can’t work with it the same way as you would do with fields and attributes.

You need to join in the price index to be able to filter and sort based on final_price. Luckily, Magento has added a few nifty functions for us to use on the product collection; addPriceDataFieldFilter() and addFinalPrice().

To be able to achieve the logic you describe above, you would want to change your code to something like this:

$collection = $this->_productCollectionFactory->create();
    ->addCategoriesFilter(['in' => $categories])
    ->addPriceDataFieldFilter('%s >= %s', ['final_price', $price_from])
    ->addPriceDataFieldFilter('%s <= %s', ['final_price', $price_to])

Note: addFinalPrice() added after the addPriceDataFieldFilter()

Print the collection query

echo $collection->getSelect()->__toString(); 

Solution 2

Try FieldToFilter instead of AttributeToFilter

$collection = $this->_productCollectionFactory->create();

$collection = $this->_productCollectionFactory->create();    
$collection = $searchedProducts->addAttributeToSelect('*')
                        ->addFieldToFilter('final_price', array(
                                array('gt' => $pricefrom, 'lt' => $priceto),

Solution 3

Using where clouse

$collection = $this->_productCollectionFactory->create();

$collection->getSelect()->where("price_index.min_price > ".$pricefrom)->where("price_index.min_price < ".$priceto)

The solution of price range filter in Magento 2 save your time.

Related Post on Add Multiple Sitemap Into One In Website

Like us on Facebook and Linkedin for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top