In this tutorial, I will be throwing light on How to Add Link with Content to Top Menu in Magento 2.
Sometimes you may require to add a custom link on the top navigation menu in Magento 2. Other than the category, you may need to add some important links so that the information reaches the customers easily.
Let’s see How to Add a Link with Content to Top Menu in Magento 2. But before that, it’s necessary to create a file that is required for creating any module like module.xml, registration.php.
Steps to Add Link with Content to Top Menu in Magento 2:
Step 1: Go to the below file path
app\code\Vendor\Extension\etc\frontend\events.xml
Now, add the code as follows
1 2 3 4 5 6 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="page_block_html_topmenu_gethtml_before"> <observer name="vendor_extension_observer" instance="Vendor\Extension\Observer\Topmenu" /> </event> </config> |
Step 2: Then move to the below file location
app\code\Vendor\Extension\Observer\Topmenu.php
Add the code as mentioned below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\Observer as EventObserver; use Magento\Framework\Data\Tree\Node; use Magento\Framework\Event\ObserverInterface; class Topmenu implements ObserverInterface { public function execute(EventObserver $observer) { $menu = $observer->getMenu(); $tree = $menu->getTree(); $data = [ 'name' => __('Menu item label link'), 'id' => 'some-unique-id-here', 'url' => 'url goes here', 'is_active' => ‘true’ ]; $node = new Node($data, 'id', $tree, $menu); $menu->addChild($node); return $this; } } ?> |
Step 3: Finally, run the below command
1 |
php bin/magento cache:flush |
Result: The link is added to the top menu in Magento 2.
Conclusion:
This way you can easily add a custom link to the top menu in Magneto 2. Fix the issue of the Navigation Menu not showing in Magento 2 – Click Here
If you have any doubts, ask me through the comment section without hesitation. Share the article with your friends and stay in touch with us!
Happy Coding!
Hardcoded $data[‘is_active’] = true?
If I add two links this way, both of them get the .active class.
According to the requirement, you have to add class by tricking the above code.
how to create newlink before what’s new menu
you need to create “After Plugin” of the function and make the alternation into the result.