I need to exclude specific attribute products in the category and search collection. I have created beforePrepareProductCollection from the 'Magento\Catalog\Model\Layer' Class. It is working fine. But It also excludes products from the category page and makes the pagination from 24 to 23. The pagination should be of 24

1 Answer 1


I have done same by hiding products from guest user. You will have to change your attribute code instead of my "hide_for_guest".


namespace Vendor\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Psr\Log\LoggerInterface;

class HideListingProduct implements ObserverInterface
    protected $customerSession;
    protected $productCollectionFactory;
    protected $logger;

    public function __construct(
        CustomerSession $customerSession,
        ProductCollectionFactory $productCollectionFactory,
        LoggerInterface $logger
    ) {
        $this->customerSession = $customerSession;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->logger = $logger;

    public function execute(\Magento\Framework\Event\Observer $observer)
        if (!$this->customerSession->isLoggedIn()) {
            $collection = $observer->getEvent()->getCollection();

            if ($collection) {
                $collection->addAttributeToFilter('hide_for_guest', ['neq' => 1]);


<?xml version="1.0"?>
<!-- Observer for SEarch and listing Page -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_block_product_list_collection">
        <observer name="hide_products_for_guest" instance="Vendor\Module\Observer\HideListingProduct" />
  • it is not working. Commented May 13 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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