Magento 2

Add Custom menu collection in Magento 2

What do we do if we want to show our own menu collection than the traditional list of menu that comes from adding categories ?
Simple just make Plugin for that.
Assuming you all know how to declare your modules i will skip that part.

app/code/Vendor/Menu/etc/di.xml

<?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=”catalogTopmenu” disabled=”true” /> <!– disable the plugin that adds the categories –>
<plugin name=”vendor-menu” type=”Vendor\Menu\Plugin\Menu” />
</type>
</config>

app/code/Vendor/Menu/Plugin/Menu.php

<?php
namespace Vendor\Menu\Plugin;

use Magento\Framework\Data\Tree\NodeFactory;

class Menu
{
/**
* @var NodeFactory
*/
protected $nodeFactory;

public function __construct(
NodeFactory $nodeFactory
) {
$this->nodeFactory = $nodeFactory;
}

public function beforeGetHtml(
\Magento\Theme\Block\Html\Topmenu $subject,
$outermostClass = ”,
$childrenWrapClass = ”,
$limit = 0
) {
$menu = $subject->getMenu();
$node = $this->nodeFactory->create(
[
‘data’ => [
‘name’ => __(‘Menu’),
‘id’ => ‘unique-id’,
‘url’ => ‘url’,
‘has_active’ => false,
‘is_active’ => false // (expression to determine if menu item is selected or not)
],
‘idField’ => ‘id’,
‘tree’ => $menu->getTree()
]
);
$subNode = $this->nodeFactory->create(
[
‘data’ => [
‘name’ => __(‘SubMenu1’),
‘id’ => ‘unique-id’,
‘url’ => ‘url’,
‘has_active’ => false,
‘is_active’ => false // (expression to determine if menu item is selected or not)
],
‘idField’ => ‘id’,
‘tree’ => $menu->getTree()
]
);
$node->addChild($subNode);
unset($subNode);
$menu->addChild($node);
// you can add other menu like this. $node for parent and sunNode for submenu of parent one
}
}

 4,070 total views

Leave a Reply

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