In this post I am going to explain how to get list of store categories in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_storeManager;
protected $_categoryCollection;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollection,
array $data = []
)
{
$this->_storeManager = $storeManager;
$this->_categoryCollection = $categoryCollection;
parent::__construct($context, $data);
}
public function getStoreCategories()
{
$currentStore = $this->_storeManager->getStore();
$storeCategories = $this->_categoryCollection->create()
->addAttributeToSelect('*')
->addAttributeToFilter('is_active', 1)
->setStore($currentStore);
return $storeCategories;
}
Add below code snippet in template file.
// Get current store's categories
$storeCategories = $block->getStoreCategories();
echo "<pre>";
print_r($storeCategories->getData());
echo "</pre>";
foreach ($storeCategories as $category) {
echo $category->getId() . '<br />';
echo $category->getName() . '<br />';
echo $category->getUrl() . '<br />';
}
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//Get current store
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
// Get current store's categories
$categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$storeCategories = $categoryCollection->create();
$storeCategories->addAttributeToSelect('*')
->addAttributeToFilter('is_active', 1)
->setStore($currentStore);
echo "<pre>";
print_r($storeCategories->getData());
echo "</pre>";
if ($storeCategories && count($storeCategories) > 0) {
foreach ($storeCategories as $category) {
echo $category->getId() . '<br />';
echo $category->getName() . '<br />';
echo $category->getUrl() . '<br />';
}
}Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply