I am want to know how to add programmatically a new link (to the main top menu in the header) with a submenu.
How to achieve that, via XML or via (PHP) plugin?
Thanks in advance.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityIf you want to add a link to your theme, then the path should be:
app/design/<VendorName>/<ThemeName>/Magento_Customer/layout/default.xml
In case if you want to add a link in your module, then the path should be:
app/code/<VendorName>/<ModuleName>/view/frontend/layout/default.xml
Now, for creating the default.xml file at the above-given path we need to add the following code:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="top.links">
<block class="Magento\Customer\Block\Account\SortLink" name="order-history-top-link" after="wish-list-link">
<arguments>
<argument name="path" xsi:type="string">custom/header/link</argument>
<argument name="label" xsi:type="string" translate="true">New Link</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
add the “Contact Us” link in the header. For that, you need to add the following code in the default.xml file.
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="header.links">
<block class="Magento\Framework\View\Element\Html\Link" name="contact-top-header-link">
<arguments>
<argument name="path" xsi:type="string">contact</argument>
<argument name="label" xsi:type="string" translate="true">Contact Us</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
Override topmenu.phtml in your theme as below
/public_html/app/design/frontend/Your/Theme/Magento_Theme/templates/html/topmenu.phtml
and add new li for each menu like below
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Top menu for store
*
* @var $block \Magento\Theme\Block\Html\Topmenu
*/
$columnsLimit = $block->getColumnsLimit() ?: 0;
$_menuHtml = $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"}}}'>
<?= /* @noEscape */ $_menuHtml?>
<?= $block->getChildHtml() ?>
<li title="Contact Us" class="level0 nav-200 level-top ui-menu-item"><a href="<?php echo $this->getUrl('contact'); ?>" class="level-top ui-corner-all"><span>Contact Us</span></a></li>
</ul>
</nav>
you can add submenu li as per your requirement
structure should be same as default magento structure
Note: you can copy html from brower (your menu and submenu's html)