Any website’s header is the perfect place to display the important links. Top Links block in Magento 2 is used to add links related to customer account like Login, Logout, My Account, My Wishlist etc.

So, in this post I am going to explain how to add top link in magento 2.

First, Add or Modify below content default.xml file

<?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="Ht\Mymodule\Block\Toplink" name="add-new-top-link">
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Top Link</argument>
                    <argument name="path" xsi:type="string" translate="true">top-link</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

Now add the Block file Toplink.php for the custom Link.

Path: app/code/Ht/Mymodule/Block/Toplink.php

<?php

namespace Ht\Mymodule\Block;

class Toplink extends \Magento\Framework\View\Element\Html\Link {

	protected function _toHtml() {
        if (false != $this->getTemplate()) {
            return parent::_toHtml();
        }
        return '<li class="custom-top-link"><a ' . $this->getLinkAttributes() . ' >' . $this->escapeHtml($this->getLabel()) . '</a></li>';
    }
}

Thats it. Now, Clear the cache the check for the change.

If you do not want to use the custom Block then you can use Magento default Block. In this case you don’t need to add the Block file.

<?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="add-new-top-link">
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Top Link</argument>
                    <argument name="path" xsi:type="string" translate="true">top-link</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

Now if you want to get or show link from your template file then you can do as below.

Add or Modify below content default.xml file

<?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="add-new-top-link" template="Ht_Mymodule::toplink.phtml" />
        </referenceBlock>
    </body>
</page>

Now add new template and add below code in that.

<li class="custom-top-link">
    <a href="#">Custom Top Link</a>
</li>

Thats it. Enjoy Magento 2!!