Need to block some CMS pages from the non-logged-in customers
Using an observer and Events
<?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_cms_page_view">
<observer name="add_login_checker" instance="<vendor>\<plugin>\Observer\RestrictCmsPage"/>
</event>
</config>
<?php
namespace <vendor>\<plugin>\Observer;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class RestrictCmsPage implements ObserverInterface
{
protected $_actionFlag;
protected $_cmsPage;
public function __construct(
CustomerSession $customerSession,
\Magento\Framework\App\ActionFlag $actionFlag,
\Magento\Cms\Model\Page $cmsPage,
\Magento\Framework\App\Response\RedirectInterface $redirect
) {
$this->customerSession = $customerSession;
$this->_actionFlag = $actionFlag;
$this->_cmsPage = $cmsPage;
$this->redirect = $redirect;
}
public function execute(Observer $observer)
{
if($this->_cmsPage->getIdentifier() == "your_identifier_name"){
if (!$this->customerSession->authenticate()) {
$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
if (!$this->customerSession->getBeforeUrl()) {
$this->customerSession->setBeforeUrl($this->redirect->getRefererUrl());
}
}
}
return $this;
}
}
Getting the page ID or page identifier
Using Object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cmsPage = $objectManager->get('\Magento\Cms\Model\Page');
echo $cmsPage->getIdentifier(); //Get Current CMS Page Identifier
echo $cmsPage->getId(); //Get Current CMS Page ID
using the Factory method
protected $_cmsPage;
public function __construct(
...
\Magento\Cms\Model\Page $cmsPage,
...
) {
...
$this->_cmsPage = $cmsPage;
...
}
echo $this->_cmsPage->getIdentifier(); //Get Current CMS Page Identifier
echo $this->_cmsPage->getId(); //Get Current CMS Page ID