0

I want to exclude specific category products from the search results collection, for example, if a customer is not logged in I don't want to show products in search results whose category id is 35. Any idea? enter image description here

2 Answers 2

0

We have to change in code in case of search product - We have to change the search functionality . means when search product happened then collect the product data without category 35, Means by code we can add this functionality

0

Use have to write Plugin file like

<?php
namespace Vendor\Module\Plugin\Catalog\Model\ResourceModel\Product;

use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Customer\Model\Session as CustomerSession;

class ProductCollectionPlugin
{
    protected $customerSession;

    public function __construct(
        CustomerSession $customerSession
    ) {
        $this->customerSession = $customerSession;
    }

    public function beforeLoad(ProductCollection $subject, $printQuery = false, $logQuery = false)
    {
        if (!$this->customerSession->isLoggedIn()) {
            // Change the category ID you want to exclude
            $excludedCategoryId = 35;

            // Exclude products from the specified category
            $subject->addCategoriesFilter(['nin' => $excludedCategoryId]);
        }

        return [$printQuery, $logQuery];
    }
}

Its an idea to prevent that category if you want to hide products you will have to change the collection

1
  • what if a product is assigned to multiple categories, like category 35 and 40, in this case it should display in search results Commented May 10 at 11:00

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.