How to Add a Top Link in Magento 2?

How to Add a Top Link in Magento 2?

[Updated June 9, 2025] Want to improve your store’s navigation for better user engagement?

Adding a top link in Magento 2 improves your customer's journey. It helps enhance navigation, engages users, and results in increased store conversion rates.

This tutorial explains how to add custom top links in Magento using XML.

Key Takeaways

  • Use header top links for strategic customer navigation on your Magento site.

  • Set up a custom Magento module and a dev environment before adding top links.

  • Use layout XML to add static or conditional links.

  • Use XML attributes to control the link display order.

  • Remove unwanted top links using the remove="true" attribute.

  • Add a CSS class in XML to style Magento links.

What are Top Links in Magento 2?

Description of Top Links in Magento 2

"Top links are navigational elements in the header. They appear on every page of your store. Default links include "My Account" and "Sign In"/"Sign Out"."

Custom links direct users to important pages. These pages include "About Us" or "Contact Us".

Top/custom links are key elements to boost store user engagement. Via strategic link placement, they guide customer navigation, contributing to better

  • Customer Lifetime Value (CLTV),

  • Customer Satisfaction (CSAT), and

  • Bounce, retention, and conversion rates.

The header is the first element users see. Important information resides in the header. This encourages visitors to explore your website. Top links serve this purpose. They provide quick access to key sections. This improves the shopping experience for customers.

Prerequisites for Adding Top Links in Magento 2

  • Fundamental Magento 2 knowledge and familiarity with its file structure and XML.

  • Access to the Magento 2 installation files. A custom module is the method for implementing changes.

  • A custom module separates customizations from core files. This action makes the code simple to maintain and upgrade.

  • A development environment for testing. This setup allows for testing changes without affecting a live site.

  • Command-line access to your Magento root directory. You will run commands to enable your module and clear the cache.

2 Methods to Add Top Links in Magento 2

Method 1: Using Layout XML in a Custom Module

The primary method to add top links involves editing the layout XML files. It is clean and upgrade-safe. Custom modules best preserve these changes, maintaining the modularity of your code.

Step 1: Create a Custom Module

  • First, create a new module to contain all the custom code. Let's name the module Vendor_TopLink. Create the necessary directories for this module.

  • Create the app/code/Vendor/TopLink directory. Inside this directory, create an etc folder. Inside etc, create a module.xml file. This file defines your new module.

<?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="Vendor_TopLink" setup_version="1.0.0"></module>
</config>
  • Next, create the registration.php file. This file registers the module with Magento. Place it in the app/code/Vendor/TopLink directory.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_TopLink',
    __DIR__
);

Step 2: Create the Layout XML File

This file will add your custom link to the header.

  • Create a view/frontend/layout directory. Inside it, create a default.xml file. The default.xml file applies to all frontend pages.

  • The path will be app/code/Vendor/TopLink/view/frontend/layout/default.xml. Add the following code to this file. This XML code adds a "Contact Us" link.

<?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="contactus.link">
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Contact Us</argument>
                    <argument name="path" xsi:type="string">contact</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>
  • This code references the header.links block. It then adds a new block of type Magento\Framework\View\Element\Html\Link. The label argument sets the link text. The path argument sets the URL for the link.

Step 3: Enable the Module and Clear Cache

After creating the files, enable your module. Open your terminal and navigate to your Magento root.

  • Run the setup upgrade command.
php bin/magento setup:upgrade
  • This command enables the Vendor_TopLink module. It also applies any necessary database changes. After the command completes, clear the Magento cache.
php bin/magento cache:flush
  • Clearing the cache ensures your changes are visible. Now, visit your store's frontend. You should see the new "Contact Us" link. The link will appear in the header section.

Clearing the Magento Cache To See the New Contact Us Link

Method 2: Adding Links Conditionally

Sometimes, you need to display links conditionally. For instance, a link might only show for logged-in users. Or, it might appear only for guest visitors. Magento's layout XML allows for this flexibility.

Displaying a Link for Logged-in Customers

To show a link only to logged-in customers, you need a custom block. This block will contain the logic for the display.

  • To create a block and a template file, first, update your default.xml file. The new block will use a custom class.
\<referenceBlock name="header.links"\>
    \<block class="Vendor\\TopLink\\Block\\Link" name="custom.link" template="Vendor\_TopLink::link.phtml" /\>
\</referenceBlock\>
  • Now, create the block class Link.php. Place it in app/code/Vendor/TopLink/Block/Link.php.
<?php
namespace Vendor\TopLink\Block;

use Magento\Framework\View\Element\Html\Link as HtmlLink;
use Magento\Customer\Model\Session as CustomerSession;

class Link extends HtmlLink
{
    protected $customerSession;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        CustomerSession $customerSession,
        array $data = []
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context, $data);
    }

    protected function _toHtml()
    {
        if ($this->customerSession->isLoggedIn()) {
            return parent::_toHtml();
        }
        return '';
    }
}
  • This block checks for logged-in customers. It uses the Magento\Customer\Model\Session object for this. If there is any customer logged in, it renders the link. Otherwise, it returns an empty string.

  • Once complete, create the template file link.phtml. Place it in app/code/Vendor/TopLink/view/frontend/templates/link.phtml.

<li>
    <a href="<?php echo $this->getUrl('custom/page'); ?>">
        <?php echo $this->escapeHtml(__('My Custom Link')); ?>
    </a>
</li>

This template defines the HTML for your link. After adding these files, clear the cache. The link will now only appear for logged-in users.

Customizing Link Position in Magento 2

You can control the position of your custom link. The before and after attributes help here. These attributes position your link relative to others.

For example, to place your link before the "My Account" link.

<referenceBlock name="header.links">
    <block class="Magento\Framework\View\Element\Html\Link" name="my.custom.link" before="my-account-link">
        <arguments>
            <argument name="label" xsi:type="string">My Link</argument>
            <argument name="path" xsi:type="string">custom/path</argument>
        </arguments>
    </block>
</referenceBlock>

The before="my-account-link" attribute positions the new link before the "My Account" link. Likewise, after="register-link" would place it after the "Create an Account" link.

Knowing the names of default links is important. Common link names include register-link, authorization-link, and wish-list-link.

Removing Top Links

You can also remove existing top links. This is useful for simplifying the header. The process resembles adding a link. You use the default.xml file.

Use the codes below to remove the “Create Account”, “Wishlist”, and/or “Compare” links.

<referenceBlock name="header.links">
    <!-- Remove Create Account link -->
    <referenceBlock name="register-link" remove="true" />
    
    <!-- Remove Wishlist link -->
    <referenceBlock name="wish-list-link" remove="true" />
    
    <!-- Remove Compare link -->
    <referenceBlock name="compare-link" remove="true" />
</referenceBlock>

The remove="true" attribute tells Magento to remove the block. You can remove any link by referencing its name. This provides a simple way to customize the header.

Styling Your Custom Top Links

Styling Custom Top Links in Magento 2

You can choose to style your link after adding it. You can use CSS to change its appearance and add a custom CSS class to your link.

  • In your default.xml file, add the class argument.
<block class="Magento\Framework\View\Element\Html\Link" name="contactus.link">
    <arguments>
        <argument name="label" xsi:type="string">Contact Us</argument>
        <argument name="path" xsi:type="string">contact</argument>
        <argument name="class" xsi:type="string">custom-contact-link</argument>
    </arguments>
</block>
  • Now, you can target this link with CSS. Create a custom CSS file in your theme. Add your styles for the .custom-contact-link class. This allows full control over the link's appearance.

For example, in your theme's CSS file:

.header.links .custom-contact-link a {
    color: #ff0000;
    font-weight: bold;
}

This CSS will make your custom link red and bold. Remember to clear the cache after adding CSS changes. Your custom styles will then apply to the link.

FAQs

1. Why is my custom top link not showing up?

Your Magento cache might contain old layout files. You should clear all caches after code changes. An incorrect module registration can cause this issue. Confirm the custom module has an enabled status. XML syntax errors prevent the layout from loading. Check your default.xml file for any errors.

2. How do I add an icon to a top link?

You add a CSS class to your link block. Use layout XML to define a custom class argument. Your theme’s CSS file then targets this new class. Use the ::before pseudo-element for adding an icon font. This method separates styling from the link structure.

3. Can I add an external URL to a top link?

You can add links to an external website. You cannot use the path argument for this. Instead, you create a custom block or template. The template contains a standard HTML <a> tag. Set the external URL inside the href attribute.

4. How do I translate a top link for different store views?

Magento's system handles the translation of link text. Use the translate="true" attribute inside your XML. Add link text to your theme’s translation CSV file. This file resides within the theme's i18n directory. Each language needs its own translation list entry.

5. Why do top links disappear after a Magento upgrade?

Magento upgrades can overwrite the core layout files. Your custom theme might override the main header block. Check for extension conflicts after an upgrade. A custom module is the safest implementation method. This method minimizes conflicts with Magento core updates.

6. Is it better to use an extension for adding links?

Extensions provide a simple interface for most users. They are a good choice for non-technical people. Custom code provides a high degree of flexibility. Developers can add their own logic and conditions. Choose based on your technical skill and needs.

Summary

Adding a top link in Magento 2 enhances navigation. The process requires a custom module for clean implementation. Below are the tutorial highlights to add a top link without error:

  • Create a custom module with registration.php and module.xml. This isolates your changes from core files.

  • Define the new link inside a default.xml layout file. Use the header.links block as a reference.

  • Specify the link's text and URL path as arguments. Use the label and path arguments for this.

  • Enable the module and clear the Magento cache. Run bin/magento setup:upgrade and bin/magento cache:flush.

  • Position or style the link using XML attributes or CSS. The before, after, and class attributes offer control.

Consider Managed Magento Hosting to simplify your store display and development workflow.

Sayan Chakraborty
Sayan Chakraborty
Technical Writer

Sayan is a seasoned technical writer with over 4 years of expertise in SDLCs and Magento. His proficiency lies in simplifying complex Magento hosting concepts in clear, concise words.


Get the fastest Magento Hosting! Get Started