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,

Feel free to comment if you run into some issue.
Check out some other posts related to menu,
Be the first to comment.