How to Add Link with Content to Top Menu in Magento 2

How to Add Link with Content to Top Menu in Magento 2

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

<?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

<?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

php bin/magento cache:flush

Result: The link is added to the top menu in Magento 2.

top menu

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!

Previous Article

How to Filter by Multiple SKU on Admin Product Grid in Magento 2?

Next Article

How To Configure Default Page Layout In Magento 2

Write a Comment
  1. Hardcoded $data[‘is_active’] = true?
    If I add two links this way, both of them get the .active class.

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨