I want to add custom links to the topmen / a submenu in the topmenu (I need the links for custom filters). To achieve this, I have created a plugin:
app/code/Vendor/Module/etc/frontend/di.xml:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<!-- Plugin to add custom topmenu links -->
<type name="Magento\Theme\Block\Html\Topmenu">
<plugin name="Module-topmenu" type="Vendor\Module\Plugin\Block\Topmenu" sortOrder="1"/>
</type>
</config>
app/code/Vendor/Module/Plugin/Block/Topmenu.php:
namespace Vendor\Module\Plugin\Block;
class Topmenu
{
/**
* @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
) {
$node = $this->nodeFactory->create(
[
'data' => $this->getNodeAsArray(),
'idField' => 'unique-id',
'tree' => $subject->getMenu()->getTree()
]
);
$subject->getMenu()->addChild($node);
}
protected function getNodeAsArray()
{
return [
'name' => 'Testlink',
'id' => 'testlink',
'url' => 'http://www.example.com/',
'has_active' => false,
'is_active' => false // (expression to determine if menu item is selected or not)
];
}
}
But this does not work, the custom menu link won't appear. Is there an error in my code, or is there another way to add topmenu/submenu links that are not categories?
EDIT: The code seems to be correct. But the site uses a customized theme that did not call the Magento function to render the menu, thus the plugin never ran. Instead, the theme builds the menu "by hand". This issue is nonexistent.