Add custom link in header in Magento 2

In this blog,  I want to share with you how to create a header link in your Magento 2 site.

Before we begin, if you don’t know how to create a simple custom module in Magento 2, please follow Step 1 in our guide here.

Now let’s code!

Step 1: We will create a CMS page. For example, we create a “Custom Link” page  with an URL such as //domain.com/custom_link

Step 2: Create a default.xml file in the following path:  app\code\Vendor\Module\view\frontend\layout with the following content:

<?xml version="1.0"?>
<page xmlns:xsi="//www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="header.links">
            <block class=”Vendor_name\Module_name\Block\Link" name="some_link" >
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Custom link</argument>
                    <argument name="path" xsi:type="string">test</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

For more details, the previous XML is used to register a Block Class in “Vendor_name\Module_name\Block\Link” . Then, set the Label and URL path for it in the arguments tag.

Step 3: Create the Block class Link with the following content:

<?php
namespace Vendor\Module\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>';
    }
}

Well done, we just completed it. If your code works fine, it should be like the one that I created inside this image: a Membership Plans link beside the sign-in button on top of the page.

Otherwise, if your code doesn’t work or you face any problems in the process of adding a custom header link in Magento 2, our Magento experts are here to help. Don’t hesitate to contact us for more consultancy and solutions.

Latest Insights

How to Start a Shopify Store in Just Over an Hour Course

Don't want to miss out on our latest insights?
Subscribe to our newsletter.

Disclaimer: By clicking submit, you agree to share your information with us to receive news, announcements, and resources when they are available.

Smart Marketing Strategies for Shopify Stores
Reveal the secret to growing your store and becoming a six-figure business.