Is there a way to get category tree list and limit the depth of it on the Magento 2 main category left sidebar subcategories list? Currently the list goes like this:
Categories:
- Subcategory 1
- Subcategory 2
- Subcategory 3
- Subcategory 4
...
The file which generates this list is within Magento_Catalog/templates/navigation/left.phtml
with the following structure:
?>
<?php if (!$block->getCategory()) {
return;
} ?>
<?php $_categories = $block->getCurrentChildCategories(); ?>
<?php $_count = is_array($_categories) ? count($_categories) : $_categories->count(); ?>
<?php if ($_count): ?>
<div class="block filter">
<div class="title">
<strong><?php /* @escapeNotVerified */ echo __('Shop By') ?></strong>
</div>
<div class="content">
<strong class="subtitle"><?php /* @escapeNotVerified */ echo __('Shopping Options') ?></strong>
<dl class="options" id="narrow-by-list2">
<dt><?php /* @escapeNotVerified */ echo __('Category') ?></dt>
<dd>
<ol class="items">
<?php foreach ($_categories as $_category): ?>
<?php if ($_category->getIsActive()): ?>
<li class="item">
<a href="<?php /* @escapeNotVerified */ echo $block->getCategoryUrl($_category) ?>"<?php if ($block->isCategoryActive($_category)): ?> class="current"<?php endif; ?>><?php echo $block->escapeHtml($_category->getName()) ?></a>
<span class="count"><?php /* @escapeNotVerified */ echo $_category->getProductCount() ?></span>
</li>
<?php endif; ?>
<?php endforeach ?>
</ol>
</dd>
</dl>
</div>
</div>
<?php endif; ?>
I would like to show subcategory tree with depth 2 so it shows lvl2 subcategories also beneath it's parent category:
Categories:
- Subcategory 1
Subcategory 1.1
Subcategory 1.2
Subcategory 1.3
- Subcategory 2
Subcategory 2.1
Subcategory 2.2
Subcategory 2.3
- Subcategory 3
Subcategory 3.1
Subcategory 3.2
Subcategory 3.3
...
Best Answer
We've created an extension that does exactly that: https://github.com/Sebwite/magento2-category-sidebar.
$category
has a functiongetChildrenNodes()
that returns all children. The function only works when flat categories are enabled. We use this function to retrieve subcategories for a category:I was having with display of category and did some work around and edited code at 2 different files. You have hard coded root category id as 1 but my root cat id was 2, So in block/sidebar.php, I changed it to store root category. and 2nd I have changed. copy following code from page-layout/2columns-left.xml and paste in layout/default.xml Remove page-layout directory.