How to Remove Specific Category From Category Menu programmatically in Magento 2

Written by Jigar Patel

Jun 18, 2023

How to Remove Specific Category From Category Menu programmatically in Magento 2

In Magento 2, the Topmenu is a core block responsible for rendering the main navigation menu at the top of the website. It displays the hierarchical structure of categories and subcategories, allowing customers to navigate through different sections of the online store.

The Topmenu block is defined in the vendor/magento/module-theme/view/frontend/templates/html/topmenu.phtml template file. This block is typically rendered in the header section of the theme layout.

The Topmenu block retrieves the menu items from the category tree, applying any necessary filters and sorting according to the configuration settings. It generates the HTML markup for the menu items, including links, dropdowns, and submenus.

The Topmenu functionality can be customized by overriding the default template file or by extending the Magento\Catalog\Plugin\Block\Topmenu class in a custom module. This allows you to modify the menu structure, add custom menu items, apply custom styling, or remove specific categories from the menu programmatically, as per your requirements.

Remove a specific category from the category menu programmatically in Magento 2, I have created a preference for the class Magento\Catalog\Plugin\Block\Topmenu. Here’s an example of how you can achieve this:

Step 1: Create Dependency injection(di.xml)

Create di.xml in app/code/Dolphin/Customize/etc directory with the following code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Plugin\Block\Topmenu"
                type="Dolphin\Customize\Plugin\Catalog\Block\Topmenu"/>
</config>

Step 2: Create class file

Create Topmenu.php file inside the app/code/Dolphin/Customize/Plugin/Catalog/Block directory with the following code.

<?php

declare(strict_types=1);

namespace Dolphin\Customize\Plugin\Catalog\Block;

use Magento\Catalog\Model\Category;
use Magento\Framework\Data\Collection;
use Magento\Framework\Data\Tree\Node;
use Magento\Catalog\Model\ResourceModel\Category\StateDependentCollectionFactory;

/**
 * Plugin for top menu block
 */
class Topmenu extends \Magento\Catalog\Plugin\Block\Topmenu
{

    /**
     * @var StateDependentCollectionFactory
     */
    private $collectionFactory;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;
    /**
     * @var \Magento\Catalog\Model\Layer\Resolver
     */
    private $layerResolver;

    /**
     * Initialize dependencies.
     *
     * @param \Magento\Catalog\Helper\Category $catalogCategory
     * @param StateDependentCollectionFactory $categoryCollectionFactory
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Catalog\Model\Layer\Resolver $layerResolver
     * @return void
     */
    public function __construct(
        \Magento\Catalog\Helper\Category $catalogCategory,
        StateDependentCollectionFactory $categoryCollectionFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver
    ) {
        $this->catalogCategory = $catalogCategory;
        $this->collectionFactory = $categoryCollectionFactory;
        $this->storeManager = $storeManager;
        $this->layerResolver = $layerResolver;

        parent::__construct(
            $catalogCategory,
            $categoryCollectionFactory,
            $storeManager,
            $layerResolver
        );
    }

    /**
     * Get Category Tree
     *
     * @param int $storeId
     * @param int $rootId
     * @return \Magento\Catalog\Model\ResourceModel\Category\Collection
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getCategoryTree($storeId, $rootId)
    {

        /** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $collection */
        $collection = $this->collectionFactory->create();
        $collection->setStoreId($storeId);
        $collection->addAttributeToSelect('name');

        $collection->addAttributeToFilter('name', ["neq"=>"Tenish Hub"]); //change category name

        $collection->addFieldToFilter('path', ['like' => '1/' . $rootId . '/%']); //load only from store root
        $collection->addAttributeToFilter('include_in_menu', 1);
        $collection->addIsActiveFilter();
        $collection->addNavigationMaxDepthFilter();
        $collection->addUrlRewriteToResult();
        $collection->addOrder('level', Collection::SORT_ORDER_ASC);
        $collection->addOrder('position', Collection::SORT_ORDER_ASC);
        $collection->addOrder('parent_id', Collection::SORT_ORDER_ASC);
        $collection->addOrder('entity_id', Collection::SORT_ORDER_ASC);

        return $collection;
    }
}

Now execute the below command and go to the system configuration page:

php bin/magento s:up
php bin/magento s:d:c
php bin/magento s:s:d -f
php bin/magento c:c

Result:- 

The first image in which category Tenish Hub is being displayed in the menu. And in the second image, the category Tenish Hub is removed from the menu.

How to Remove Specific Category From Category Menu programmatically in Magento 2

 

How to Remove Specific Category From Category Menu programmatically in Magento 2

 

 

I Hope, This instruction will be helpful for you.

If you have any difficulties regarding this blog, do consider posting them in the Comments section below!

I’m here to help.

Thank you!

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP