2

I would like to filter product collection on category page using custom attribute. For example:

On category page, I want to list only products that have custom attribute age set to 10.

How to achieve that? Thanks

2 Answers 2

4

You can make preference of this class Magento\Catalog\Block\Product\ListProduct

and go to its _getProductCollection() method and put your attribute filter condition after this line

$this->_productCollection = $layer->getProductCollection();

for example

  $this->_productCollection = $layer->getProductCollection();
  $this->_productCollection->addAttributeToFilter('age', 10);

Update

In case of MagentoCE2.2 that method would be initializeProductCollection()

9
  • 1
    I'm in version 2.2, which I/m working in that line is in function initializeProductCollection(). Worked fines. Thanks! Commented May 23, 2018 at 13:05
  • You are always welcome @PeteJaworski Commented May 23, 2018 at 16:18
  • This is private method so we can't override this.we can change private to public but don't want to make any changes in core file so how can modify the method "initializeProductCollection()". Commented Sep 12, 2018 at 7:36
  • When we apply a filter on category product collection the products will display as we needed but the Layered navigation display will not be driven from the loaded collection but it was driven from the whole category products. So, how to resolve this issue.? Commented Jun 28, 2019 at 10:30
  • @MurtuzaZabuawala, how can we filter collection with multi-select attribute? Commented Oct 11, 2019 at 9:53
2

For the drop-down attribute, We can filter using drop-down option ID instead of Label.

Your code is like below.

$_productCollection = $block->getLoadedProductCollection();
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('age', 10)
    ->load();

I hope it will work for you.

1
  • Which class plugin shall I use it in? Commented May 23, 2018 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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