Magento2 Categories – Get All Categories on Same Level

categorycategory-treemagento2

We use the following helper to get the current category:

class Category extends \Magento\Framework\View\Element\Template
{
    protected $_registry;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {        
        $this->_registry = $registry;
        parent::__construct($context, $data);
    }

    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    public function getCurrentCategory()
    {        
        return $this->_registry->registry('current_category');
    }

    public function getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }    

}

In our template file that works perfect using $category = $block->getCurrentCategory() and also to get all child categories $subcategories = $category->getChildrenCategories();

But now we want to also load all categories that are on the same level as the current category. So not the child categories, but the ones that are on the same level.

So how can we get all categories that are on the same level? Seems quit hard

Best Answer

You can simply use below 2 lines once you have fetched current category

$pcategory = $category->getParentCategory();
$subcats = $pcategory->getChildrenCategories();