I'm trying to add filters to a product collection on the category page.

I wanted to create an observer that listens to catalog_product_collection_load_before, but I found out that the even is not fired anymore in the changelog.

How can I filter the product collection, without this observer. Should I use a plugin? Where to start?


Alright, I did figure it out myself based on this question. If anyone else faces this problem, the way to go is indeed to create a plugin.

Create the file frontend/di.xml:

<?xml version="1.0"?>
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
        <plugin name="sidebarFilters" type="Sebwite\Sidebar\Model\Plugin\SidebarFilter"/>

Then create the plugin:

<?php namespace Sebwite\Sidebar\Model\Plugin;

use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;

class SidebarFilter
     * aroundAddFieldToFilter method
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
     * @param \Closure                                                $proceed
     * @param                                                         $fields
     * @param null                                                    $condition
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
    public function aroundAddFieldToFilter(ProductCollection $collection, \Closure $proceed, $fields, $condition = null)
        // Here we can modify the collection

        return $fields ? $proceed($fields, $condition) : $collection;
| improve this answer | |
  • Can you show some example ? I would like to filter by some custom attribute but can't find a way.. – Yonn Trimoreau Jun 27 '16 at 9:29
  • Hi Silvan do you know how to set default filter on each category? – Akshay Jindal Jul 24 '16 at 9:19
  • @AkshayJindal just use the code above and add a filter on the collection: $collection->addAttributeToFilter('brand', ['in' => ['brand1', brand2']]); – Silvan Jul 25 '16 at 10:04
  • This solution no working for the LayeredNavigation and pagination – Carlos Hernan Aguilar Hurtado Jul 27 at 19:45

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.