cancel
Showing results for 
Search instead for 
Did you mean: 

Add Filter to magento 2 category product collection

Add Filter to magento 2 category product collection

Hello, a similar problem.
If i want filter product collection, create plugin for Layer (if use event the result will be the same).

<type name="Magento\Catalog\Model\Layer">
<plugin name="LayerPlugin" type="MyModule\Module\Model\Plugin\Layer"/>
</type>

Code LayerPlugin (filter product collection by type_id):

 

 

class Layer {
    public function afterGetProductCollection($subject, $collection) {
        $collection->addAttributeToFilter('type_id', array('eq' => 'simple'));
        return $collection;
    }
}

 

The collection is correct and show only 2 products.

But the Pagination oder Category Filter show 9 Products.

 

Why??

 

 

 

5 REPLIES

Re: Add Filter to magento 2 category product collection

Hi @Ehrling,



I can see that you are filtering by simple products. Maybe the other products in the category are configurable/grouped/etc.


Could you please double-check that?

 


Best regards.

Gabriel

If my answer was useful, please give "Kudos" to this post.
If my answer helps you to resolve the problem, click on "Accept as Solution".

Re: Add Filter to magento 2 category product collection

Hi!

 

yes, the other products are configurable,...

to Filter by type_id is only an example. You can use any productattribute for this issue.

Re: Add Filter to magento 2 category product collection

any idea?

Re: Add Filter to magento 2 category product collection

Try to add $collection->getSize(); after your code so it recalculates sizes again, before $collection->load()

Re: Add Filter to magento 2 category product collection

See this video, I hope it can help

https://www.youtube.com/watch?v=ZuBax1UKNhA

It is a tutorial on How to get product collection in Magento 2.