How to Hide Header(Primary) Menu before login (for Visitors)?
-
06-10-2020 - |
Question
Magento 2 Version - Magento 2.1.4 CE
I am trying to create Custom Module for Compulsory login.
When user hits the website url it must needs to redirect on login screen and after logged in user can surf or visit our website.
So Compulsory login functionality i have already done by creating custom module.
Here the issue is how to hide menu ? before login(visitors) ?
i want to hide header menu for visitors. once user is logged in then and then menu will show otherwise it needs to be hide.
Hope it clears.
Update :
I know by overriding the topmenu.phtml i can achieve this. but issue here is if i override topmenu.phtml then myaccount,logout links in dropdown are disappear.
Check below screenshot :
Solution
Override Magento_Theme::view/frontend/templates/html/topmenu.phtml and use this code in the file:
<?php $columnsLimit = $block->getColumnsLimit() ?: 0; ?>
<?php $_menu = $block->getHtml('level-top', 'submenu', $columnsLimit) ?>
<nav class="navigation" data-action="navigation">
<ul data-mage-init='{"menu":{"responsive":true, "expanded":true, "position":{"my":"left top","at":"left bottom"}}}'>
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
// customer login action
echo $_menu;
}
?>
<?php /* @escapeNotVerified */ echo $block->getChildHtml(); ?>
</ul>
</nav>
Though, using objectmanager is not a good practice, so you may override block file too.
to override topmenu.phtml, follow this:
In your module the template needs to be placed here:
app/code/VENDORNAME/MODULENAME/view/frontend/templates/html/topmenu.phtml
Additionally, a layout definition is required:
app/code/VENDORNAME/MODULENAME/view/frontend/layout/default.xml
and put this in default.xml:
<?xml version="1.0"?>
<page layout="1columns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock class="Magento\Theme\Block\Html\Topmenu" name="catalog.topnav" template="VENDORNAME_MODULENAME::html/topmenu.phtml" ttl="false"/>
</body>
</page>
OTHER TIPS
Check the answer @Raphael How to check if customer is logged in or not in magento 2?
Based on that is the user logged or not, you can change the template of the theme that you are using to show/hide the main menu: The main menu is render here: /vendor/magento/module-theme/view/frontend/templates/html/topmenu.phtml
You can check here how template to be customized: http://devdocs.magento.com/guides/v2.1/frontend-dev-guide/templates/template-overview.html