1

I am trying to add class to the top menu item in Magento. I was able to add class to the <li> tag by overriding the Topmenu.php file. Now I want to add a class to the <a> tag too. Below is the Topmenu.php content. I have added the class nav-item to the <li> tag and it works. Similarly, I want to add a class to the <a> tag under the <li>

<?php

namespace Ecommerce\Menu\Block\Html;

class Topmenu extends \Magento\Theme\Block\Html\Topmenu
{
    protected function _getMenuItemClasses(\Magento\Framework\Data\Tree\Node $item)
    {
        $classes = [];

        $classes[] = 'level' . $item->getLevel();
        $classes[] = $item->getPositionClass();

        if ($item->getIsFirst()) {
            $classes[] = 'first';
        }

        if ($item->getIsActive()) {
            $classes[] = 'active';
        } elseif ($item->getHasActive()) {
            $classes[] = 'has-active';
        }

        if ($item->getIsLast()) {
            $classes[] = 'last';
        }

        if ($item->getClass()) {
            $classes[] = $item->getClass();
        }

        if ($item->hasChildren()) {
            $classes[] = 'parent';
        }

        $classes[] = 'nav-item';

        return $classes;
    }
}

1 Answer 1

0

I've try with jquery and php with your code, but i've another best way to add class.

class Link extends \Magento\Framework\View\Element\Html\Link implements SortLinkInterface {
protected $_template = 'Mymodule_Customer::my-custom-link.phtml';

Now you have to create the file Mymodule/Customer/view/frontend/templates/my-custom-link.phtml

<li class="the-class-you-want-to-use">
<a class="child" <?php echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel())?></a>

another solution

<block class="Magento\Customer\Block\Account\SortLinkInterface" name="customer-account-navigation-orders-link-2">
<arguments>
    <argument name="path" xsi:type="string">sales/order/history</argument>
    <argument name="label" xsi:type="string" translate="true">My Orders 2</argument>
    <argument name="sortOrder" xsi:type="number">230</argument>
    <argument name="attributes" xsi:type="array">
        <item name="class" xsi:type="string">my_custom_link</item>
    </argument>
</arguments>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.