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

6

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()

| improve this answer | |
  • 1
    I'm in version 2.2, which I/m working in that line is in function initializeProductCollection(). Worked fines. Thanks! – Pete Jaworski May 23 '18 at 13:05
  • You are always welcome @PeteJaworski – Murtuza Zabuawala May 23 '18 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()". – wakar Ahamad Sep 12 '18 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.? – gajjala sandeep Jun 28 '19 at 10:30
  • @MurtuzaZabuawala, how can we filter collection with multi-select attribute? – jafar pinjar Oct 11 '19 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.

| improve this answer | |
  • Which class plugin shall I use it in? – Pete Jaworski May 23 '18 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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