Displaying Only Level 0 Categories in Magento Navigation Menu
If you’re looking to display only top-level (level 0) categories in your Magento navigation menu, you’ve come to the right place. In this post, we’ll guide you through the process with a step-by-step approach that requires minimal coding.
Understanding Your Current Setup
Before diving into the solution, let’s understand what’s currently happening:
<?php echo $this->getChildHtml('topMenu') ?>
This line of code is retrieving and displaying the topMenu block in your layout. By default, this block will contain all categories, including subcategories.
Displaying Only Level 0 Categories
Method 1: Using Layout XML (Recommended)
The cleanest way to achieve this is by modifying your layout XML file. Here’s how:
-
Open
app/design/frontend/<Your_Theme>/layout/default.xmlor create it if it doesn’t exist. -
Add the following content inside the
<body>tags:
<reference name="topmenu">
<action method="setUseAnchor"><arg>true</arg></action>
<action method="checkChild"><level>0</level><levels>1</levels></action>
</reference>
The checkChild action with <level>0</level> ensures that only top-level categories are displayed. The <levels>1</levels> argument indicates the number of subcategories to include, set to 0 for no subcategories.
Save and refresh your cache: php bin/magento cache:flush.
Method 2: Modifying the phtml File
If you prefer a code-based approach, you can modify the topmenu.phtml file:
-
Open
app/design/frontend/<Your_Theme>/template/page/html/topmenu.phtml. -
Locate this line (around line 65):
$children = $this->getChildren();
- Replace it with:
$children = $this->getChildren(0);
The getChildren method accepts an argument indicating the depth level of categories to retrieve. Passing 0 ensures only top-level categories are fetched.
- Save and refresh your cache:
php bin/magento cache:flush.
Conclusion
Displaying only level 0 categories in your Magento navigation menu is a straightforward process that can be achieved through layout XML modifications or by directly editing the phtml file.
For more advanced customizations and best practices, I recommend exploring the official Magento documentation on Catalog Category Display Settings and the Magento 2 core codebase for a deeper understanding of how these settings work under the hood. You can access the full codebase at their GitHub repository: https://github.com/magento/magento2.
Remember to always backup your files before making any changes, follow version control best practices, and thoroughly test your modifications before deploying them to a live environment.
Happy coding! Let me know if you have any other questions or need further assistance with Magento development.