Magento 2 can restrict access to specific categories by leveraging observers and event handling. Here’s how you can achieve this:
1)Create an Observer:
Create a custom observer class that implements MagentoFrameworkEventObserverInterface. This observer will listen to the controller_action_predispatch_catalog_category_view event.
<?php
namespace VendorModuleObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoFrameworkAppResponseRedirectInterface;
use MagentoCustomerModelSession as CustomerSession;
class RestrictCategoryAccess implements ObserverInterface
{
protected $customerSession;
protected $redirect;
public function __construct(
CustomerSession $customerSession,
RedirectInterface $redirect
) {
$this->customerSession = $customerSession;
$this->redirect = $redirect;
}
public function execute(MagentoFrameworkEventObserver $observer)
{
if (!$this->customerSession->isLoggedIn()) {
$categoryIdsToRestrict = [1, 2, 3]; // Replace with your category IDs
$categoryId = (int) $observer->getEvent()->getRequest()->getParam('id');
if (in_array($categoryId, $categoryIdsToRestrict)) {
$this->redirect->redirect($observer->getEvent()->getResponse(), 'customer/account/login');
}
}
}
}
2)Configure the Observer:
Declare your observer in the events.xml file of your module to listen to the controller_action_predispatch_catalog_category_view event.
<?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="controller_action_predispatch_catalog_category_view"> <observer name="restrict_category_access" instance="VendorModuleObserverRestrictCategoryAccess" /> </event> </config>