How to Add Custom Header Link in Magento 2

In this tutorial we are going to show you how to add custom header link in Magento 2, Adding header link in Magento 2 means showing some helpful links on the top of your pages.

For this, we are going to use a custom module to add header link in Magento 2.

Now let’s code!

Step 1: First of all, Create module.xml file in app/code/MageBeginners/Addheaderlink/etc.

<?xml version="1.0"?>
            <config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="MageBeginners_Addheaderlink" setup_version="1.0.1"></module>

Step 2: Register Module, Create registration.phpfile in app/code/MageBeginners/Addheaderlink.


Step 3: Create default.xmlfile in app/code/MageBeginners/Addheaderlink/view/frontend/layout.

<?xml version="1.0"?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
     <referenceBlock name="header.links">
         <block class="MageBeginners\Addheaderlink\Block\Link" name="custom-header-link">
     <argument name="label" xsi:type="string" translate="true">Contact Us</argument>
     <argument name="path" xsi:type="string" translate="true">contact</argument>

In the code above, I have added the contact us page link. You can change it according to your need.

Step 4: Create Link.phpfile in app/code/MageBeginners/Addheaderlink/Block .

namespace MageBeginners\Addheaderlink\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>';

Step 5: 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

Step 6: Open your store and you will see the new link Contact Us:

How to Add Custom Header Link in Magento 2 Click To Tweet

We hope this article helped you learn how to add custom header link in Magento 2. You may also want to see our list of How to Enable SSL Certificate in Magento 2.

If you liked this article, then please subscribe to our Newsletter for Magento tutorials. You can also find us on Twitter and Facebook. If you have any problem or would like to add to the discussion, leave a comment below!

You May Also Like

Editorial Staff

About the Author: Editorial Staff

Editorial Staff at the MageBeginners is a team of Magento experts writing about Magento Tutorials, Themes, Extensions, Guides, Tricks and much more...

Leave a Reply

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