Back to Top

How to add link in Category Menu in Magento 2

Updated 1 March 2024

In this blog, I’ll explain how you can add link in category menu.

First, create di.xml under [Namespace]/[Module]/etc/frontend/ folder with following content,

<?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="offer-topmenu" type="[Namespace]\[Module]\Plugin\Block\Topcat" />
    </type>
</config>

Then create Topcat.php under [Namespace]/[Module]/Plugin/Block/ folder,

<?php
namespace [Namespace]\[Module]\Plugin\Block;

use Magento\Framework\Data\Tree\NodeFactory;

class Topcat
{
    public function __construct(
        NodeFactory $nodeFactory,
        \Magento\Framework\UrlInterface $urlInterface
    ) {
        $this->nodeFactory = $nodeFactory;
        $this->urlInterface = $urlInterface;
    }

    public function beforeGetHtml(
        \Magento\Theme\Block\Html\Topmenu $subject,
        $outermostClass = '',
        $childrenWrapClass = '',
        $limit = 0
    ) {
        $node = $this->nodeFactory->create(
            [
                'data' => $this->getNodeAsArray(),
                'idField' => 'id',
                'tree' => $subject->getMenu()->getTree()
            ]
        );
        $subject->getMenu()->addChild($node);
    }

    public function getNodeAsArray()
    {
        return [
            'name' => __('Offers'),
            'id' => 'mpcampaign-offers-menu',
            'url' => $this->urlInterface->getUrl('mpcampaign/offer'),
            'has_active' => false,
            'is_active' => $this->isActive()
        ];
    }
    
    private function isActive()
    {
        $activeUrls = 'mpcampaign/offer';
        $currentUrl = $this->urlInterface->getCurrentUrl();
        if (strpos($currentUrl, $activeUrls) !== false) {
            return true;
        }
        return false;
    }
}

It will add the menu in the category menu section as shown below,

new cat menu

Feel free to comment if you run into some issue.

Searching for an experienced
Magento 2 Company ?
Find out More

Check out some other posts related to menu,

https://webkul.com/blog/header-and-top-links-in-magento-2/

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home