Magento – Add custom menu links only to mobile menu layout

magento2.2.2menunavigationtopmenu

I am using Magento 2.2.2 and I am trying to add some custom menu links to magento in the mobile menu layout.

I tried adding a custom block with menu links by referring catalog.topnav block

default.xml

<referenceBlock name="catalog.topnav">
        <block class="Magento\Theme\Block\Html\Topmenu" name="custom.catalog.topnav" template="Mymodule_TopMenu::html/topmenu.phtml"/>
    </referenceBlock> 

topmenu.phtml

<li class="custom-menu">
    <a href="<?php echo $block->getUrl('about-us'); ?>">About Us</a>
</li>

After doing so, the menu links are getting added to the navigation menu bar. And i am using a custom css to hide those menus from desktop layout. Only in mobile layout i am displaying it.

The problem is the menu links needs to be present in the navigation menu bar so as to display in the mobile layout as well. But i wanted to render my custom menu links only in mobile menu layout.

How can i achieve it ? Please suggest some approach.

Best Answer

File Path: app/code/Solwin/Module1/view/frontend/layout/default.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright info.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="store.menu">
            <block name="store.menu.logo" template="Solwin_Module1::html/topmenu_custom.phtml" after="catalog.topnav" />
        </referenceBlock>
    </body>
</page>

File Path:app/code/Solwin/Module1/view/frontend/templates/html/topmenu_custom.phtml

<?php
/** @var \Magento\Framework\View\Element\Template $block */
?>
<ul class="ui-custom-menu">
  <li class="ui-custom-menu-tem">
      <a href="<?php echo $this->getBaseUrl()."/custommenu1"; ?>" class="level-top">
          <span><?= __("CustomMenu1")?></span>
      </a>
  </li>
  <li class="ui-custom-menu-tem">
      <a href="<?php echo $this->getBaseUrl()."/custommenu2"; ?>" class="level-top">
          <span><?= __("CustomMenu2")?></span>
      </a>
  </li>
</ul>

<style>
.ui-custom-menu {
  margin: 0;
  padding: 0;
}
.ui-custom-menu-tem {
    border-top: 1px solid #d1d1d1;
    font-size: 1.6rem;
    margin: 0;
}
.ui-custom-menu-tem .level-top {
    font-weight: 700;
    padding: 8px 40px 8px 15px;
    text-transform: uppercase;
    word-wrap: break-word;
    color: #575757;
    text-decoration: none;
    display: block;
}
</style>
Related Topic