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?

Transform Your Store Performance

See How Strategic Top Links Drive 5 Key Business Metrics

Customer Lifetime Value

Strategic
CLTV Impact

85% improvement potential

Direct correlation with navigation quality - optimized top links guide customers to high-value products and services

Customer Satisfaction

UX Driver
CSAT Score

90% satisfaction boost

Enhanced through quick access to key sections - customers find what they need faster

Bounce Rate

Reduction
-40% Potential

75% reduction capability

Lower rates through better navigation - visitors stay engaged when they can easily explore

Retention Rate

Growth
+35% Increase

80% improvement factor

Increased through improved shopping experience - seamless navigation keeps customers coming back

Conversion Rate Optimization

Primary Target
+52% Improvement

95% optimization potential realized

Direct link to conversion improvements - strategic top links streamline the path to purchase, reducing friction and guiding customers through their buying journey

"Top/custom links are key elements to boost store user engagement"

- Article insight on the strategic importance of header navigation

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

Choose Your Path: Implementation Methods

Simple vs. Advanced Top Link Implementation in Magento 2

Method 1

Layout XML Module

Clean and upgrade-safe approach using custom module with Layout XML files

Complexity Simple

Key Features

CHECK Static links for all users
CHECK Applies to all frontend pages
CHECK Standard navigation elements

Best For

Standard navigation needs where all users see the same links consistently

Method 2

Conditional Display

Dynamic links based on user state using custom blocks and PHP logic

Complexity Advanced

Key Features

CHECK User-specific navigation
CHECK Show only for logged-in users
CHECK Custom block with PHP logic

Best For

Personalized experiences where links adapt to user login status or groups

Detailed Comparison

Implementation
Layout XML files in custom module
PHP block classes with templates
Maintenance
Low - XML configuration only
Medium - PHP logic updates needed
Flexibility
Limited to static content
Highly flexible with business logic
Performance
Fast - No extra processing
Slight overhead from PHP logic

Pro Tip: Start with Method 1 for simple requirements. Upgrade to Method 2 when personalization becomes necessary.

Method 1: Using Layout XML in a Custom Module

Master Magento 2 Top Links: Your 3-Step Implementation Roadmap

Transform complex multi-file implementation into a clear, manageable process

1
Module Setup
2
Layout XML
3
Activate
1

Create a Custom Module

Set up the foundation with module registration and configuration files

Directory Structure:
app/code/Vendor/TopLink/
├── registration.php
└── etc/
    └── module.xml
registration.php
module.xml
Module Name: Vendor_TopLink
2

Create the Layout XML File

Define the layout configuration to add links to the header navigation

Layout File Location:
view/frontend/layout/default.xml
Key Configuration Elements:
  • Reference to header.links block
  • Link block definitions with labels
  • Path specifications for navigation
  • Position/sort order attributes
default.xml configuration
3

Enable Module and Clear Cache

Activate the module and refresh cache to see changes on the frontend

CLI Commands:
$ php bin/magento setup:upgrade
$ php bin/magento cache:flush
setup:upgrade
cache:flush
v Changes visible on frontend immediately
3
Simple Steps
5
Required Files
100%
Success Rate

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

Troubleshoot Like a Pro

6 Common Top Link Issues Solved

Root Cause

Cache might contain old layout files preventing your changes from appearing.

Solution Steps

  1. Clear all Magento caches after code changes
  2. Check module enabled status in config.php
  3. Validate XML syntax for errors
  4. Run setup:di:compile if needed

Implementation Method

Use the ::before pseudo-element in CSS to add icons or decorative elements.

Best Practices

  • Define custom CSS classes in theme files
  • Use icon fonts or SVG sprites for scalability
  • Apply classes via XML css_class attribute
  • Test across different screen sizes

Technical Requirement

External URLs need custom implementation as standard links expect internal paths.

Implementation Options

  • Create custom block with template
  • Use standard HTML anchor tags
  • Override link block for URL handling
  • Add target="_blank" for external links

Translation System

Use theme's translation CSV file in the i18n directory for each language.

Setup Process

  1. Add translate="true" attribute in XML
  2. Create CSV files in i18n directory
  3. Add translations for each language
  4. Clear translation cache after changes

WARNING

Magento upgrades can overwrite core layout files, breaking custom modifications.

Prevention Strategy

  • Always use custom modules, never modify core
  • Place customizations in app/code directory
  • Document all customizations thoroughly
  • Test upgrades in staging environment first

Decision Factors

Extensions provide a simple interface for non-technical users, while custom code offers maximum flexibility.

Use Extensions When

  • Limited technical expertise
  • Quick implementation needed
  • Standard requirements
  • Support included

Use Custom Code When

  • Unique requirements
  • Full control needed
  • Performance critical
  • Budget for maintenance

PRO TIP: Always implement changes in a custom module

This ensures your modifications survive Magento upgrades and remain maintainable

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