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??
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
Hi!
yes, the other products are configurable,...
to Filter by type_id is only an example. You can use any productattribute for this issue.
any idea?
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.
Any solution for this issue?
How to apply filter on category page?
Let’s say I want to get product collection filter by product ids
Note: Please override files in the custom module. I just gave a solution with core file modification.
vendor/magento/module-catalog-search/etc/search_request.xml
<request query="catalog_view_container" index="catalogsearch_fulltext"> <queries> <query xsi:type="boolQuery" name="catalog_view_container" boost="1"> <queryReference clause="should" ref="entity_id"/> </query> <query xsi:type="filteredQuery" name="entity_id"> <filterReference clause="should" ref="entity_id_filter"/> </query> </queries> <filters> <filter xsi:type="termFilter" name="entity_id_filter" field="entity_id" value="$entity_id$"/> </filters> </request>
vendor/magento/module-catalog/Model/Layer.php
public function getProductCollection() { if (isset($this->_productCollections[$this->getCurrentCategory()->getId()])) { $collection = $this->_productCollections[$this->getCurrentCategory()->getId()]; } else { $collection = $this->collectionProvider->getCollection($this->getCurrentCategory()); $collection->addFieldToFilter('entity_id', [1,2,3]); $this->prepareProductCollection($collection); $this->_productCollections[$this->getCurrentCategory()->getId()] = $collection; } return $collection; }
HI @Ehrling
I am facing same issue. Did you get any solution for that ?