I want to add some link to navigation menu in magento 2. Some link will display after checking customer logged in or not. I tried to create a plugin.
namespace AIS\Custom\Plugin;
use Magento\Framework\Data\Tree\NodeFactory;
class Topmenu
{
protected $nodeFactory;
protected $customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
NodeFactory $nodeFactory
) {
$this->customerSession = $customerSession;
$this->nodeFactory = $nodeFactory;
}
public function beforeGetHtml(
\Magento\Theme\Block\Html\Topmenu $subject,
$outermostClass = '',
$childrenWrapClass = '',
$limit = 0
) {
$node = $this->nodeFactory->create(
[
'data' => $this->getProviderNode(),
'idField' => 'id',
'tree' => $subject->getMenu()->getTree()
]
);
$subject->getMenu()->addChild($node);
if($this->customerSession->isLoggedIn()) {
$node = $this->nodeFactory->create(
[
'data' => $this->getMyCourseNode(),
'idField' => 'id',
'tree' => $subject->getMenu()->getTree()
]
);
$subject->getMenu()->addChild($node);
}
}
protected function getProviderNode()
{
return [
'name' => __('Provider'),
'id' => 'nav-provider',
'url' => 'http://www.example.com/',
'has_active' => false,
'is_active' => false // (expression to determine if menu item is selected or not)
];
}
protected function getMyCourseNode()
{
return [
'name' => __('My Course'),
'id' => 'nav-mycourse',
'url' => 'http://www.example.com/',
'has_active' => false,
'is_active' => false // (expression to determine if menu item is selected or not)
];
}
protected function getCacheLifetime()
{
return 0;
}
}
All page seems fine but the home page is not following the checking. It will display "My Course" button after customer logout. I try to disable the cache and it cannot fix the problem.