Skip to main content
1 of 2
Silvan
  • 1.4k
  • 6
  • 33
  • 55

Magento 2 no Layered Navigation after filter collection

We've added a default filter for our product collection by adding a plugin:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\Layer">
        <plugin name="filterCatalog" type="Silvan\StockStatus\Plugin\Catalog\Model\Layer" sortOrder="10"/>
    </type>
</config>

And the class:

<?php namespace Silvan\StockStatus\Plugin\Catalog\Model;

class Layer
{
    /**
     * afterGetProductCollection method
     *
     * @param                                                                $subject
     * @param \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $collection
     *
     * @return mixed
     */
    public function afterGetProductCollection($subject, $collection)
    {
        $collection->addAttributeToSelect('bgs_stock_status');
        $collection->addAttributeToFilter(
            [
                ['attribute' => 'bgs_stock_status', 'is' => new \Zend_Db_Expr('null')],
                ['attribute' => 'bgs_stock_status', 'lt' => 3],
            ]);

        $collection->getSize();

        return $collection;
    }
}

But as soon as we add the 'addAttributeToFilter' part, all Layered Navigation filter options are gone. If we remove this code it's shown again.

How can we filter our product collection, without losing the filter attributes? There are enough products to show filters.

Silvan
  • 1.4k
  • 6
  • 33
  • 55