Please try below code to get the first level category collection in your template phtml file:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//get current category
$collection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory')->create();
$collection->addAttributeToFilter('level', array('eq' => 2));
foreach ($collection as $category) {
print_r($category->getData());
}
?>
Note: Direct use of objectManager
is not recommended. Try to create the function in your block class and use it in the template.
Also, you can get the Parent Categories and check the level in for loop!
use \Magento\Framework\Registry $registry
...
public function getCategoryCollection(){
$currentCategory = $this->_registry->registry('current_category');
if($currentCategory){
if($currentCategory->getParentCategories()){
foreach ($currentCategory->getParentCategories() as $parent) {
//check level
if ($parent->getLevel() == 1) {
return $parent->getId();
}
}
}
}
return null;
}
Or try to inject the \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
class in your block class
use \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollection
public function getCategoryCollection()
{
// $level = 2;
$collection = $this->_categoryCollection->create()
->addAttributeToSelect('*')
// ->setStore($this->_storeManager->getStore())
->addAttributeToFilter('level', array('eq' => 2));
// ->addLevelFilter($level); OR
->addAttributeToFilter('is_active','1');
return $collection;
}
Hope this helps!