Category tree for left sidebar

Hi, I’m trying to build a category tree for the left sidebar. Therefore my plan was to always get the current category id:

 public function getCurrentCategoryId() { return $this->layerResolver->get()->getCurrentCategory()->getId(); } 

And get the current categoryId passed in to the category factory to get the corresponding children.

 public function getChildCategories($categoryId) { $category = $this->categoryFactory->create(); $categoryCollection = $category->load($categoryId); //Get category collection return $categoryCollection->getCollection() ->addNavigationMaxDepthFilter() ->addUrlRewriteToResult() ->addIsActiveFilter() ->addAttributeToFilter('include_in_menu', 1) ->addAttributeToSelect('*') ->setOrder('position', 'ASC') ->addIdFilter($categoryCollection->getChildren()); } 

In the .phtml, I simply loop through:

<?php $currentCategoryId = $this->getCurrentCategoryId(); $categories = $this->getChildCategories($currentCategoryId); ?> <?php foreach ($categories as $category): ?> <div class=""> <a href="<?= $block->escapeUrl($category->getUrl()) ?>" class=""><span><?= $block->escapeHtml(__($category->getName())) ?></span> </a> </div> <?php endforeach; ?> 

This is working. However, I’m quite not there, because on the last level I want to show all categories of the last level.

Example of structure:

-category level 0 -category level 1 -category level 1 -category level 2 -category level 2 

At the moment it’s like this:

Click on category level 0 in topmenu -> it will show all category level 1 in sidebar: That’s good

Click on category level 1 in sidebar -> it will show all category level 2 in sidebar: That’s good

Click on category level 2 in sidebar -> it will show nothing anymore in sidebar: That’s bad, because here I want to show all level 2 categories so that users can switch between these categories of the last level.

Maybe my approach is wrong but since I’m almost there, I don’t think I’m on the complete wrong path, am I? Just need to fix this last issue.

Any help would be appreciated. Thanks

submitted by /u/zlep
[link] [comments]