How to remove a category from being displayed in Magento 2 for users who are not logged in or belong to a specific customer group using an observer?*

Step 1: Define the Event Observer

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_category_collection_load_after">
        <observer name="restrict_category_observer"
                  instance="JJRestrictPageObserverRestrictCategory"/>
    </event>
</config>

Step 2: Implement the Observer

<?php


namespace JJRestrictPageObserver;


use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoCustomerModelSession as CustomerSession;
use MagentoCatalogModelResourceModelCategoryCollection;


class RestrictCategory implements ObserverInterface
{
    protected $customerSession;


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


    public function execute(Observer $observer)
    {
        // Get logged-in user status and group ID
        $customerGroupId = $this->customerSession->getCustomerGroupId();
        $isLoggedIn = $this->customerSession->isLoggedIn();


        // If the user is not logged in OR not in group 4, remove "Best Selling" category
        if (!$isLoggedIn || $customerGroupId != 4) {
            /** @var Collection $categoryCollection */
            $categoryCollection = $observer->getEvent()->getCategoryCollection();


            foreach ($categoryCollection as $category) {
                if ($category->getName() == "Best selling") { // Adjust the category name if needed
                    $categoryCollection->removeItemByKey($category->getId());
                }
            }
        }
    }
}

Leave a comment

Your email address will not be published. Required fields are marked *