Hello Everyone,
In this blog, we will learn about how to add Custom Header and Top Link in Magento 2.
Header link is displayed for both guest and logged in customer.
Top link is displayed for only logged in customers.
Without wasting your time, let us guide you straight away. Follow the easy step given below to Add Custom Header and Top Link in Magento 2.
STEPS FOR ADD CUSTOM HEADER AND TOP LINK IN MAGENTO 2
Step 1: Create default.xml file
app/code/Vendor/Extension/view/frontend/layout/default.xml
<?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=”Magento\Framework\View\Element\Html\Link” name=”header-menu”>
<arguments>
<argument name=”label” xsi:type=”string” translate=”true”>Custom Header Menu</argument>
<argument name=”path” xsi:type=”string”>*/*/*</argument>
</arguments>
</block>
</referenceBlock>
<referenceBlock name=”top.links”>
<block class=”Magento\Framework\View\Element\Html\Link” name=”top-link”>
<arguments>
<argument name=”label” xsi:type=”string” translate=”true”>Custom Top Link</argument>
<argument name=”path” xsi:type=”string”>*/*/*</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
Step 2: Finally run the below commands
$ php bin/magento cache:flush
Step 3: Output:
For Guest User

For Logged in User

If you want to add custom block in your custom header or top link follow the below steps.
Step 1: Create default.xml file
app/code/Vendor/Extension/view/frontend/layout/default.xml
<?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=”Vendor\Extension\Block\Customlink” name=”header-menu”>
<arguments>
<argument name=”label” xsi:type=”string” translate=”true”>Custom Header Menu</argument>
<argument name=”path” xsi:type=”string”>*/*/*</argument>
</arguments>
</block>
</referenceBlock>
</body>
</page>
Step 2: Create Customlink.php file
app/code/Vendor/Extension/Block/Customlink.php
<?php
namespace Vendor\Extension\Block;
class Customlink extends \Magento\Framework\View\Element\Html\Link
{
/**
* Render block HTML.
*
* @return string
*/
protected function _toHtml() {
if (false != $this->getTemplate()) {
return parent::_toHtml();
}
$label = $this->escapeHtml($this->getLabel());
return ‘<li><a ‘ . $this->getLinkAttributes() . ‘ >’ . $label . ‘</a></li>’;
}
}
Final Thoughts:
So this was the easiest way which we have told you in this blog. This is how you can Add Custom Header and Top Links in Magento 2. Hope you liked the blog.
So quickly go to the comment box and tell me how you like this blog?
Stay tuned with us on our site to get new updates of Magento.
Thanks for reading and visiting our site.