How to add non-category link to navigation menu in Magento 2?

In this post, I will be guiding you on how to add non-category link to the navigation menu in Magento 2.

If you still think that the container navigation.sections which holds the category links it can be referenced and passing following arguments can create a new category link under navigation menu, you are highly mistaken.

<referenceContainer name="navigation.sections">
    <block class="Magento\Framework\View\Element\Html\Links" name="mylink">
        <arguments>
            <argument name="label" xsi:type="string">Custom link</argument>
            <argument name="path" xsi:type="string">*/*/*</argument>
        </arguments>
    </block>
</referenceContainer>

The latest Magento 2 doesn’t support this kind of approach anymore.

You can use a plugin to add non-category link in the navigation menu. Follow below steps to add non-category link to the navigation menu.

Step-1: Define plugin in di.xml file

Create di.xml file in app/code/Aureatelabs/ModuleName/etc/frontend directory.

<?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="aureatelabs-non-category-link" type="Aureatelabs\ModuleName\Plugin\NonCategoryLink" />
    </type>
</config>

Step-2: Create a plugin file

Next, create NonCategoryLink.php in app/code/Aureatelabs/ModuleName/Plugin directory.

<?php
namespace Aureatelabs\ModuleName\Plugin;

use Magento\Framework\Data\Tree\NodeFactory;

class NonCategoryLink
{
    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' => __('Custom Link'),
            'id' => 'some-unique-id-here',
            'url' => 'http://www.example.com/',
            'has_active' => false,
            'is_active' => false
        ];
    }

}

Here,

  • name: Define a label that will display in the navigation menu
  • id: Add some unique id here
  • url: Add the URL for category link
  • Is_active: To determine if a menu item is selected or not

Next, run the below commands

php bin/magento setup:di:compile
php bin/magento cache:flush

Now you can see your custom non-category link in the navigation menu.

  • Share :