How to Add Non-Category Link to Navigation Links in Magento 2
The following article sheds light on how to add a non-category link to navigation links in Magento 2. If you are not sure what to do, you’ve come to the right place, because below we detailly discuss this problem.
If you still think that the block which holds the category links in can be referenced to as navigation.sections and the following arguments can be directed towards the container providing the ability to create a new link under it, you are mistaken.
1 2 3 4 5 6 7 8 9 |
<referenceContainer name="navigation.sections"> <block class="Magento\Framework\View\Element\Html\Links" name="mylink"> <arguments> <argument name="label" xsi:type="string">Mylink</argument> <argument name="path" xsi:type="string">mypath</argument> <argument name="css_class" xsi:type="string">mycss</argument> </arguments> </block> </referenceContainer> |
The latest Magento 2 version doesn’t support this approach anymore. But you can still achieve your goal!
It is necessary to replace an observer with a plugin for Magento\Theme\Block\Html\Topmenu.
- Find the etc/frontend/di.xml file.
- Add the following code to it:
1 2 3 |
<type name="Magento\Theme\Block\Html\Topmenu"> <plugin name="[module]-topmenu" type="[Namespace]\[Module]\Plugin\Block\Topmenu" /> </type> |
- Create the plugin class file [Namespace]/[Module]/Plugin/Block/Topmenu.php.
- Add the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?php namespace [Namespace]\[Module]\Plugin\Block; use Magento\Framework\Data\Tree\NodeFactory; 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' => 'id', 'tree' => $subject->getMenu()->getTree() ] ); $subject->getMenu()->addChild($node); } protected function getNodeAsArray() { return [ 'name' => __('Label goes here'), 'id' => 'some-unique-id-here', 'url' => 'http://www.example.com/', 'has_active' => false, 'is_active' => false // (expression to determine if menu item is selected or not) ]; } } |
This is the fastest way of adding a non-category link to navigation links in Magento 2. We hope the article was useful. It is based on the