When we have multi-store setup and store have different category assigned at that time we need to get store wise category collection.
We can get store wise category collection by below code snippet.
1. Use directly Objectmanager is not best/Recommended way to do in Magento, use Block with the construct() and fetch method in your phtml file.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $categoryFactory = $objectManager->create('Magento\Catalog\Helper\Category'); $categoryFactory->getStoreCategories(false,false,true);
2. Recommended Way Using Create Block file and call from the template,
Create Block PHP file,
<?php namespace Rbj\Training\Block\Index; class Training extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Helper\Category $categoryHelper, array $data = [] ) { $this->_categoryHelper = $categoryHelper; parent::__construct($context, $data); } /** * Retrieve current store level 2 category * * $sorted (if true display collection sorted as name otherwise sorted as based on id asc) * $asCollection (if true display all category otherwise display second level category menu visible category for current store) * $toLoad */ public function getMainStoreCategories($sorted = false, $asCollection = false, $toLoad = true) { return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad); } /* Here we have passed sorted as true so category display as Name ASC order */ public function getAllCurrentStoreCategories($sorted = true, $asCollection = true, $toLoad = true) { return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad); } }
Display second level category, all those categories which have Level equals 2. call below function from a template file,
$getLevel2Category = $block->getMainStoreCategories(); foreach($getLevel2Category as $category) { echo $category->getName();echo "<br>"; }
For getting all categories of current store call below function in template file,
$getCategory = $block->getAllCurrentStoreCategories(); foreach($getCategory as $category) { echo $category->getName();echo "<br>"; }
You can change the custom argument by passing argument on above function from template file.