How to Add Custom Header Link in Magento 2
- Syed Muneeb Ul Hasan
- December 18, 2017

Your website’s header is perhaps the best place to display important links and pages. There are a few links in the header section of the store by default in Magento 2. I have also seen queries asking how to add more links to the header section in Magento 2.
So today I’m going to teach you how to add header link in Magento 2. I will implement it using a custom module!
Configuration of Module
To configure the module, create module.xml file in app/code/Magenticians/Mymodule/etc and paste the following code in it:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Magenticians_Mymodule" setup_version="1.0.1"></module> </config>
Registration of Module
To register the module, create registration.php file in app/code/Magenticians/Mymodule and paste the following code in it:
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Magenticians_Mymodule', __DIR__ );
Create Layout File
Create default.xml file in app/code/Magenticians/Mymodule/view/frontend/layout and paste the following code in it:
<?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="header.links"> <block class="Magenticians\Mymodule\Block\Link" name="custom-header-link"> <arguments> <argument name="label" xsi:type="string" translate="true">Contact Us</argument> <argument name="path" xsi:type="string" translate="true">contact</argument> </arguments> </block> </referenceBlock> </body> </page>
In the code above, I have added the contact us page link. You can change it according to your need.
Create Block File
Create Link.php file in app/code/Magenticians/Mymodule/Block and paste the following code in it:
<?php namespace Magenticians\Mymodule\Block; class Link extends \Magento\Framework\View\Element\Html\Link { /** * Render block HTML. * * @return string */ protected function _toHtml() { if (false != $this->getTemplate()) { return parent::_toHtml(); } return '<li><a ' . $this->getLinkAttributes() . ' >' . $this->escapeHtml($this->getLabel()) . '</a></li>'; } }
Run CLI Commands
Go to the root directory of your store by connecting it with SSH and then run these commands:
php bin/magento setup:upgrade php bin/magento setup:di:compile php bin/magento cache:clean php bin/magento cache:flush
Open your store and you will see the new link Contact Us:
Final Words
To increase the chances of more sales, make sure all the useful pages/links of your store are visible. After following this guide, I hope you’ll be able to add a top link in Magento 2. Still facing issues in its implementation? Just drop your query in the comment box and I will get back to you!