Sometimes we need to add some important links in navigation menu except category by which customer easily find that links and they can reach our information.
We can achieve this goal by overwrite default magento file vendor/magento/module-theme/view/frontend/templates/html/topmenu.phtml. But this is not good practice by making changes in default Magento functionality.
In Magento 2 added new feature is Plugin. We will use plugin to implement this.
I have assumed that we have already installed module.In this blog we will add only files which related to this task.
1 – We have to create app/code/Test/TestCustomMenu/etc/di.xml file where we will define our plugin.
<?xml version="1.0"?> <!-- /** * @category Webkul * @package Test_TestCustomMenu * @author Webkul Software Private Limited * @license https://store.webkul.com/license.html */ --> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <!-- Add Plugin for add custom link in navigation --> <type name="Magento\Theme\Block\Html\Topmenu"> <plugin name="add_menu_item_plugin" type="Test\TestCustomMenu\Plugin\Topmenu" sortOrder="10" disabled="false"/> </type> </config>
2 – Now we have to create app/code/Test/TestCustomMenu/Plugin/Topmenu.php . In this file we will modify default getHtml function. This function return list html which is call in navigation menu.
We added after plugin of getHtml function for adding our custom link at the end of pre-generated list of html.
<?php /** * @category Webkul * @package Test_TestCustomMenu * @author Webkul Software Private Limited * @license https://store.webkul.com/license.html */ namespace Test\TestCustomMenu\Plugin; class Topmenu { /** * @param Context $context * @param array $data */ public function __construct( \Magento\Customer\Model\Session $session ) { $this->Session = $session; } public function afterGetHtml(\Magento\Theme\Block\Html\Topmenu $topmenu, $html) { $swappartyUrl = $topmenu->getUrl('testCustomMenu/custommenu');//here you can set link $magentoCurrentUrl = $topmenu->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); if (strpos($magentoCurrentUrl,'testCustomMenu/custommenu') !== false) { $html .= "<li class=\"level0 nav-5 active level-top parent ui-menu-item\">"; } else { $html .= "<li class=\"level0 nav-4 level-top parent ui-menu-item\">"; } $html .= "<a href=\"" . $swappartyUrl . "\" class=\"level-top ui-corner-all\"><span class=\"ui-menu-icon ui-icon ui-icon-carat-1-e\"></span><span>" . __("Custom Menu") . "</span></a>"; $html .= "</li>"; return $html; } }
After adding above files please run following command :-
php bin/magento setup:di:compile
php bin/magento cache:flush
Now you can check your custom link in navigation menu.
I hope this blog help you to add custom link in navigation menu.If you have any Query then please feel free to put it in comment section.
Be the first to comment.