I explain to add custom link in navigation menu for magento 2. In Navigation Menu, there are categories and subcategories links available. But, sometimes we need to add some custom links in navigation bar.
The admin under the Catalog -> Categories menu. By default, this menu will only contain categories and nothing else, and therefore a common request from merchants is how to add a custom link to the Magento 2 top menu, usually a CMS page link.
We can override topmenu.phtml file and add custom HTML content to add custom links in the navigation menu. But based on coding standards, override file is not good practice to change default functionality.
So, I have a solution that we can add custom link in navigation bar using a plugin.
Magento builds its top menu using the Magento\Catalog\Plugin\Block\Topmenu plugin via the beforeGetHtml() method.
Like to Read: [Solved]Magento 2 Navigation Menu not Showing
Now we create Dependency injection file di.xml in app/code/Dolphin/Menu/etc/frontend/di.xml with the following code.
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Theme\Block\Html\Topmenu"> <plugin name="custom_menu_item" type="Dolphin\Menu\Plugin\Topmenu" disabled="false"/> </type> </config>
Finally, add in the Plugin class. As with the default Topmenu plugin, a beforeGetHtml() method is defined, and the menu node is added as part of the Magento\Framework\Data\Tree\NodeFactory class.
Create plugin class file Topmenu.php in app/code/Dolphin/Menu/Plugin/ folder with the following code.
<?php namespace Dolphin\Menu\Plugin; use Magento\Framework\Data\Tree\NodeFactory; use Magento\Framework\UrlInterface; class Topmenu { /** * @var NodeFactory */ protected $nodeFactory; /** * @var UrlInterface */ protected $urlBuilder; /** * @param NodeFactory $nodeFactory * @param UrlInterface $urlBuilder */ public function __construct( NodeFactory $nodeFactory, UrlInterface $urlBuilder ) { $this->nodeFactory = $nodeFactory; $this->urlBuilder = $urlBuilder; } public function beforeGetHtml( \Magento\Theme\Block\Html\Topmenu $subject, $outermostClass = '', $childrenWrapClass = '', $limit = 0 ) { /** * Level1 Menu */ $menuNode = $this->nodeFactory->create( [ 'data' => $this->getNodeAsArray("Custom Menu", "custom-menu"), 'idField' => 'id', 'tree' => $subject->getMenu()->getTree(), ] ); /** * Level1-1 Child Menu */ $menuNode->addChild( $this->nodeFactory->create( [ 'data' => $this->getNodeAsArray("Custom Menu - Child Menu", "child-menu"), 'idField' => 'id', 'tree' => $subject->getMenu()->getTree(), ] ) ); $subject->getMenu()->addChild($menuNode); } protected function getNodeAsArray($name, $id) { $url = $this->urlBuilder->getUrl($id); return [ 'name' => __($name), 'id' => $id, 'url' => $url, 'has_active' => false, 'is_active' => false, ]; } }
I hope this helps you.please feel free to leave a comment below.
Keep sharing !!