If your Website is setup with multiple store and each store has different Root Category assigned, In that case you need to refer below blog for getting all root category ids by programmatically.
Let’s consider your store with Two Root Category available.
First Native Magento Default Category which id is 2.
Second, create custom Root Category based on your requirement which id is 42.
Now How to get above root category id using coding in Magento 2, You can get root category id by below way,
<?php
namespace Rbj\Root\Block;
class RootCategoryIds extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $data = []
) {
$this->_storeManager = $storeManager;
parent::__construct($context, $data);
}
/**
* Return ids of root categories as array
*
* @return array
*/
public function getRootIds()
{
$ids = [\Magento\Catalog\Model\Category::TREE_ROOT_ID];
foreach ($this->_storeManager->getGroups() as $store) {
$ids[] = $store->getRootCategoryId();
}
return $ids;
}
Call from template file,
echo "<pre>";print_r($this->getRootIds());
Output as array,
Array
(
[0] => 1
[1] => 2
[2] => 42
)
In above case 1 is for Root Catalog id,
2 is your Default Category id.
42 is your custom created root category id.
Let’s explore get category collection per store by,
Get Category Collection of specific store