Skip to main content

Magento 2: How to Get Category Collection in Magento 2?

Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php


<?php
namespace YourCompanyName\YourModuleName\Block;
class YourCustomBlock extends \Magento\Framework\View\Element\Template
{
    protected $_categoryCollectionFactory;
 
    protected $_categoryHelper;
  
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Helper\Category $categoryHelper,
        array $data = []
    ) {
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryHelper = $categoryHelper;
        parent::__construct($context, $data);
    }
  
    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false) {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');
  
        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }
  
        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }
  
        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }
  
        // set pagination
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }
  
        return $collection;
    }
  
    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true) {
        return $this->_categoryHelper->getStoreCategories($sorted = false, $asCollection = false, $toLoad = true);
    }
}
 
 
 
////////////////////////////////////////////////////////////////////
 
view (.phtml) file as follows.
 
// get the list of all categories
$categories = $block->getCategoryCollection();
foreach ($categories as $category) {
    echo $category->getId() . '<br />';
    echo $category->getName() . '<br />';
}
  
// get categories sorted by category name
$categories = $block->getCategoryCollection(true, false, 'name', false);
foreach ($categories as $category) {
    echo $category->getId() . '<br />';
    echo $category->getName() . '<br />';
}
  
// get current store’s categories
$categories = $block->getStoreCategories();
foreach ($categories as $category) {
    echo $category->getId() . '<br />';
    echo $category->getName() . '<br />';
}
 
 
 
////////////////////////////////////////////////////////////////////
Using Object Manager
 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
// get the list of all categories
$categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryCollection->create();
$categories->addAttributeToSelect('*');
  
foreach ($categories as $category) {
    echo $category->getId() . '<br />';
    echo $category->getName() . '<br />';
    echo $category->getUrl() . '<br />';
}
 
// get current store’s categories
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categories = $categoryHelper->getStoreCategories();
  
foreach ($categories as $category) {
    echo $category->getId() . '<br />';
    echo $category->getName() . '<br />';
}
 
 
 

Comments

Popular posts from this blog

Magento 2: Category list for custom magento system configuration section ( Backend )

In system.xml file field for multi select of category is like: NOTE: Use Select for Single item and multiselect for multiple in - <field id = "bannerlist" translate = "label" type = " multiselect " <group id = "bannerblock_setting" translate = "label" type = "text" delault = "1" sortOrder = "3" showInDefault = "1" showInWebsite = "1" showInStore = "1" > <label> Setting </label> <field id = "bannerlist" translate = "label" type = "multiselect" sortOrder = "10" showInDefault = "1" showInWebsite = "1" showInStore = "1" > <label> Select Category </label> <!-- <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>--> <source_model> Ipragmatech\Bannerblock\Model\Config\Source\C...

Magento 2: Add new tab in Product detail page

New tab in product detail page is very easy task with product attribute. Use below steps and check it out. Step 1. Create Product Attribute “video”. Step 2. Create file “ catalog_product_view.xml ” in the app/design/frontend/{vender name}/{theme name}/Magento_Catalog/layout In the file write the below code: <!-- this is code to add new tab start --> <referenceBlock name="product.info.details"> <block class="Magento\Catalog\Block\Product\View\Description" name="product.info.video" template="product/view/attribute.phtml" group="detailed_info"> <arguments> <argument name="at_call" xsi:type="string">getVideo</argument> <argument name="at_code" xsi:type="string">video</argument> <argument name="css_class" xsi:type="string">video</argument> <argument name="at_label" xsi:type="string">non...