Magento2 – How to Get First Level Category List

blockscategorymagento2

I'd like to list all first level categories from inside my custom block. I'd like to get the category names and the URLs.

How can I achieve this?

Best Answer

Try:

/** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $collection */
$collection = $this->collectionFactory->create();
$collection->addFieldToFilter('level', 2);
$collection->addIsActiveFilter();
$collection->setStoreId($storeId);
$collection->addUrlRewriteToResult();
$collection->addAttributeToSelect('name');

Where $storeId is your current store id. You can get it by

// \Magento\Store\Model\StoreManagerInterface $storeManager,
$storeId = $this->storeManager->getStore()->getId();

[Update]

Sample block class:

<?php


namespace VendorName\Checkout\Block;

use Magento\Catalog\Helper\Category;
use Magento\Catalog\Model\ResourceModel\Category\StateDependentCollectionFactory;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;

class Test extends Template
{
    /**
     * @var Category
     */
    private $catalogCategory;

    /**
     * @var StateDependentCollectionFactory
     */
    private $collectionFactory;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Test constructor.
     * @param Template\Context $context
     * @param Category $catalogCategory
     * @param StateDependentCollectionFactory $categoryCollectionFactory
     * @param StoreManagerInterface $storeManager
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        Category $catalogCategory,
        StateDependentCollectionFactory $categoryCollectionFactory,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->catalogCategory = $catalogCategory;
        $this->collectionFactory = $categoryCollectionFactory;
        $this->storeManager = $storeManager;
        parent::__construct($context, $data);
    }

    public function getCategories()
    {
        $storeId = $this->storeManager->getStore()->getId();
        /** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $collection */
        $collection = $this->collectionFactory->create();
        $collection->addFieldToFilter('level', 2);
        $collection->addIsActiveFilter();
        $collection->setStoreId($storeId);
        $collection->addUrlRewriteToResult();
        $collection->addAttributeToSelect('name');

        $categories = [];
        foreach ($collection as $category) {
            $categories[] = [
                'name' => $category->getName(),
                'url' => $this->catalogCategory->getCategoryUrl($category)
            ];
        }

        return $categories;
    }
}
Related Topic