Get product collection by root category and all its subcategories in Magento 2?How to get list of categories including sub categories in Magento 2?How get product IDs of root category and subcategory under root category programmatically?Getting product filter by root categoryProduct collection for subcategories of subcategoriesHow to do a list with all categories and subcategories, from a given main-categoryhow to get magento categories and set values of categories while adding a product programatically?How to get Subcategory and its products with details in magentoget product collection and subcategory id using category id magento 2Configurable Product Collection and variantsHow to check the category collection is empty or not in magento 2?How to show all categories and their subcategories on Layered Navigation?

Provisioning profile doesn't include the application-identifier and keychain-access-groups entitlements

Can the druid cantrip Thorn Whip really defeat a water weird this easily?

Does Linux have system calls to access all the features of the file systems it supports?

What does おとこえしや mean?

Making a sword in the stone, in a medieval world without magic

Decoding assembly instructions in a Game Boy disassembler

Word for a person who has no opinion about whether god exists

Rejected in 4th interview round citing insufficient years of experience

What wound would be of little consequence to a biped but terrible for a quadruped?

Is going from continuous data to categorical always wrong?

What is the definition of "Natural Selection"?

Why don't MCU characters ever seem to have language issues?

Deleting missing values from a dataset

Can infringement of a trademark be pursued for using a company's name in a sentence?

How could a female member of a species produce eggs unto death?

Do items de-spawn in Diablo?

How is the Swiss post e-voting system supposed to work, and how was it wrong?

Why would a jet engine that runs at temps excess of 2000°C burn when it crashes?

Welcoming 2019 Pi day: How to draw the letter π?

Why must traveling waves have the same amplitude to form a standing wave?

Time dilation for a moving electronic clock

How to deal with a cynical class?

US to Europe trip with Canada layover- is 52 minutes enough?

Want to switch to tankless, but can I use my existing wiring?



Get product collection by root category and all its subcategories in Magento 2?


How to get list of categories including sub categories in Magento 2?How get product IDs of root category and subcategory under root category programmatically?Getting product filter by root categoryProduct collection for subcategories of subcategoriesHow to do a list with all categories and subcategories, from a given main-categoryhow to get magento categories and set values of categories while adding a product programatically?How to get Subcategory and its products with details in magentoget product collection and subcategory id using category id magento 2Configurable Product Collection and variantsHow to check the category collection is empty or not in magento 2?How to show all categories and their subcategories on Layered Navigation?













6















How can I retrieve a product collection by a root category and from all its subcategories?



Eg:



Root Category (2 products)




  • Subcategory 1 (2 products)


  • Subcategory 2 (3 products)

So I want to retrieve all 7 products in the collection.










share|improve this question




























    6















    How can I retrieve a product collection by a root category and from all its subcategories?



    Eg:



    Root Category (2 products)




    • Subcategory 1 (2 products)


    • Subcategory 2 (3 products)

    So I want to retrieve all 7 products in the collection.










    share|improve this question


























      6












      6








      6








      How can I retrieve a product collection by a root category and from all its subcategories?



      Eg:



      Root Category (2 products)




      • Subcategory 1 (2 products)


      • Subcategory 2 (3 products)

      So I want to retrieve all 7 products in the collection.










      share|improve this question
















      How can I retrieve a product collection by a root category and from all its subcategories?



      Eg:



      Root Category (2 products)




      • Subcategory 1 (2 products)


      • Subcategory 2 (3 products)

      So I want to retrieve all 7 products in the collection.







      magento2 product category collection






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 5 mins ago









      thedash

      1037




      1037










      asked Sep 15 '16 at 12:20









      nuwausnuwaus

      91931945




      91931945




















          5 Answers
          5






          active

          oldest

          votes


















          3














          You can use like this:



          /** MagentoCatalogApiCategoryRepositoryInterface */
          protected $categoryRepository;

          /** MagentoCatalogModelResourceModelProductCollectionFactory */
          protected $productCollectionFactory;

          public function getAllProductOfSubcategories($categoryId, $storeId = null)

          /** @var $result MagentoCatalogModelResourceModelProductCollection */
          $result = $this->productCollectionFactory->create();

          //get category at $storeId
          try
          $category = $this->categoryRepository->get($categoryId, $storeId);
          catch (MagentoFrameworkExceptionNoSuchEntityException $noSuchEntityException)
          return null;


          return $result->addCategoryFilter($category);



          *Note: Your category must Enable Anchor



          Enable Anchor for Category



          *Note: run php bin/magento indexer:reindex just for make sure






          share|improve this answer
































            2














            Code for your class file:



            protected $_categoryHelper;
            protected $_categoryRepository;

            public function __construct(
            MagentoCatalogHelperCategory $categoryHelper,
            MagentoCatalogModelCategoryRepository $categoryRepository,
            array $data = []
            )

            $this->_categoryHelper = $categoryHelper;
            $this->_categoryCategoryRepository = $categoryRepository;
            parent::__construct($context, $data);


            public function getStoreCategories()

            return $this->_categoryHelper->getStoreCategories();


            public function getCategory($categoryId)

            return $this->_categoryRepository->get($categoryId);



            Code for your template file:



            $categories = $block->getStoreCategories();
            foreach ($categories as $category)
            echo $category->getName();
            echo ' ( ' . $category->getProductCount() . ' )';

            $subCategories = $block->getCategory($category->getId());
            foreach ($subCategories as $subCategory)
            echo $subCategory->getName();
            echo ' ( ' . $subCategory->getProductCount() . ' )';




            Source: Magento 2: Get parent category, children categories & product count






            share|improve this answer
































              1














              I solved it as below,



              protected $_category;
              protected $_productCollection;

              /** You should provide your root category here, and it will return comma seperated sub category list */
              public function getChildren($categoryId = false)

              if ($this->_category)
              return $this->_category->getChildren();
              else
              return $this->getCategory($categoryId)->getChildren();



              protected function _getProductCollection()

              $childListStr = $this->getChildren( 2 ); // Provide the root category ID
              $childList = explode( ",", $childListStr );
              $catToLoad = array();

              foreach( $childList as $item )
              array_push( $catToLoad, $item );


              if ($this->_productCollection === null)
              $layer = $this->getLayer();
              $this->_productCollection = $layer->getProductCollection();


              $this->_productCollection->addCategoriesFilter(['in' => $catToLoad ]);
              return $this->_productCollection;






              share|improve this answer






























                0














                Hi I have another way to get product collection from root category... check it out.. I hope this help



                public function __construct(
                MagentoCatalogModelLayerCategory $categoryLayer
                )
                $this->_categoryLayer = $categoryLayer;


                public function getProductCollection($category)
                return $this->_categoryLayer->setCurrentCategory($category)->getProductCollection();






                share|improve this answer






























                  -4














                  Try this



                   $category = Mage::getModel('catalog/category')->load(2);
                  $children = Mage::getModel('catalog/category')->getCollection()->setStoreId(Mage::app()->getStore()->getId());
                  $children->addAttributeToSelect('*')
                  ->addAttributeToFilter('parent_id', $category->getId())
                  ->addAttributeToFilter('is_active', 1)
                  ->addAttributeToSort('position');
                  foreach($children as $child)


                  $category=Mage::getModel('catalog/category')->load($child->entity_id);






                  share|improve this answer




















                  • 3





                    This is Magento 1 way.

                    – Khoa TruongDinh
                    Sep 15 '16 at 13:29










                  Your Answer








                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "479"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f136517%2fget-product-collection-by-root-category-and-all-its-subcategories-in-magento-2%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  5 Answers
                  5






                  active

                  oldest

                  votes








                  5 Answers
                  5






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  3














                  You can use like this:



                  /** MagentoCatalogApiCategoryRepositoryInterface */
                  protected $categoryRepository;

                  /** MagentoCatalogModelResourceModelProductCollectionFactory */
                  protected $productCollectionFactory;

                  public function getAllProductOfSubcategories($categoryId, $storeId = null)

                  /** @var $result MagentoCatalogModelResourceModelProductCollection */
                  $result = $this->productCollectionFactory->create();

                  //get category at $storeId
                  try
                  $category = $this->categoryRepository->get($categoryId, $storeId);
                  catch (MagentoFrameworkExceptionNoSuchEntityException $noSuchEntityException)
                  return null;


                  return $result->addCategoryFilter($category);



                  *Note: Your category must Enable Anchor



                  Enable Anchor for Category



                  *Note: run php bin/magento indexer:reindex just for make sure






                  share|improve this answer





























                    3














                    You can use like this:



                    /** MagentoCatalogApiCategoryRepositoryInterface */
                    protected $categoryRepository;

                    /** MagentoCatalogModelResourceModelProductCollectionFactory */
                    protected $productCollectionFactory;

                    public function getAllProductOfSubcategories($categoryId, $storeId = null)

                    /** @var $result MagentoCatalogModelResourceModelProductCollection */
                    $result = $this->productCollectionFactory->create();

                    //get category at $storeId
                    try
                    $category = $this->categoryRepository->get($categoryId, $storeId);
                    catch (MagentoFrameworkExceptionNoSuchEntityException $noSuchEntityException)
                    return null;


                    return $result->addCategoryFilter($category);



                    *Note: Your category must Enable Anchor



                    Enable Anchor for Category



                    *Note: run php bin/magento indexer:reindex just for make sure






                    share|improve this answer



























                      3












                      3








                      3







                      You can use like this:



                      /** MagentoCatalogApiCategoryRepositoryInterface */
                      protected $categoryRepository;

                      /** MagentoCatalogModelResourceModelProductCollectionFactory */
                      protected $productCollectionFactory;

                      public function getAllProductOfSubcategories($categoryId, $storeId = null)

                      /** @var $result MagentoCatalogModelResourceModelProductCollection */
                      $result = $this->productCollectionFactory->create();

                      //get category at $storeId
                      try
                      $category = $this->categoryRepository->get($categoryId, $storeId);
                      catch (MagentoFrameworkExceptionNoSuchEntityException $noSuchEntityException)
                      return null;


                      return $result->addCategoryFilter($category);



                      *Note: Your category must Enable Anchor



                      Enable Anchor for Category



                      *Note: run php bin/magento indexer:reindex just for make sure






                      share|improve this answer















                      You can use like this:



                      /** MagentoCatalogApiCategoryRepositoryInterface */
                      protected $categoryRepository;

                      /** MagentoCatalogModelResourceModelProductCollectionFactory */
                      protected $productCollectionFactory;

                      public function getAllProductOfSubcategories($categoryId, $storeId = null)

                      /** @var $result MagentoCatalogModelResourceModelProductCollection */
                      $result = $this->productCollectionFactory->create();

                      //get category at $storeId
                      try
                      $category = $this->categoryRepository->get($categoryId, $storeId);
                      catch (MagentoFrameworkExceptionNoSuchEntityException $noSuchEntityException)
                      return null;


                      return $result->addCategoryFilter($category);



                      *Note: Your category must Enable Anchor



                      Enable Anchor for Category



                      *Note: run php bin/magento indexer:reindex just for make sure







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Sep 18 '17 at 2:35

























                      answered Aug 16 '17 at 4:27









                      RubeliaRubelia

                      565




                      565























                          2














                          Code for your class file:



                          protected $_categoryHelper;
                          protected $_categoryRepository;

                          public function __construct(
                          MagentoCatalogHelperCategory $categoryHelper,
                          MagentoCatalogModelCategoryRepository $categoryRepository,
                          array $data = []
                          )

                          $this->_categoryHelper = $categoryHelper;
                          $this->_categoryCategoryRepository = $categoryRepository;
                          parent::__construct($context, $data);


                          public function getStoreCategories()

                          return $this->_categoryHelper->getStoreCategories();


                          public function getCategory($categoryId)

                          return $this->_categoryRepository->get($categoryId);



                          Code for your template file:



                          $categories = $block->getStoreCategories();
                          foreach ($categories as $category)
                          echo $category->getName();
                          echo ' ( ' . $category->getProductCount() . ' )';

                          $subCategories = $block->getCategory($category->getId());
                          foreach ($subCategories as $subCategory)
                          echo $subCategory->getName();
                          echo ' ( ' . $subCategory->getProductCount() . ' )';




                          Source: Magento 2: Get parent category, children categories & product count






                          share|improve this answer





























                            2














                            Code for your class file:



                            protected $_categoryHelper;
                            protected $_categoryRepository;

                            public function __construct(
                            MagentoCatalogHelperCategory $categoryHelper,
                            MagentoCatalogModelCategoryRepository $categoryRepository,
                            array $data = []
                            )

                            $this->_categoryHelper = $categoryHelper;
                            $this->_categoryCategoryRepository = $categoryRepository;
                            parent::__construct($context, $data);


                            public function getStoreCategories()

                            return $this->_categoryHelper->getStoreCategories();


                            public function getCategory($categoryId)

                            return $this->_categoryRepository->get($categoryId);



                            Code for your template file:



                            $categories = $block->getStoreCategories();
                            foreach ($categories as $category)
                            echo $category->getName();
                            echo ' ( ' . $category->getProductCount() . ' )';

                            $subCategories = $block->getCategory($category->getId());
                            foreach ($subCategories as $subCategory)
                            echo $subCategory->getName();
                            echo ' ( ' . $subCategory->getProductCount() . ' )';




                            Source: Magento 2: Get parent category, children categories & product count






                            share|improve this answer



























                              2












                              2








                              2







                              Code for your class file:



                              protected $_categoryHelper;
                              protected $_categoryRepository;

                              public function __construct(
                              MagentoCatalogHelperCategory $categoryHelper,
                              MagentoCatalogModelCategoryRepository $categoryRepository,
                              array $data = []
                              )

                              $this->_categoryHelper = $categoryHelper;
                              $this->_categoryCategoryRepository = $categoryRepository;
                              parent::__construct($context, $data);


                              public function getStoreCategories()

                              return $this->_categoryHelper->getStoreCategories();


                              public function getCategory($categoryId)

                              return $this->_categoryRepository->get($categoryId);



                              Code for your template file:



                              $categories = $block->getStoreCategories();
                              foreach ($categories as $category)
                              echo $category->getName();
                              echo ' ( ' . $category->getProductCount() . ' )';

                              $subCategories = $block->getCategory($category->getId());
                              foreach ($subCategories as $subCategory)
                              echo $subCategory->getName();
                              echo ' ( ' . $subCategory->getProductCount() . ' )';




                              Source: Magento 2: Get parent category, children categories & product count






                              share|improve this answer















                              Code for your class file:



                              protected $_categoryHelper;
                              protected $_categoryRepository;

                              public function __construct(
                              MagentoCatalogHelperCategory $categoryHelper,
                              MagentoCatalogModelCategoryRepository $categoryRepository,
                              array $data = []
                              )

                              $this->_categoryHelper = $categoryHelper;
                              $this->_categoryCategoryRepository = $categoryRepository;
                              parent::__construct($context, $data);


                              public function getStoreCategories()

                              return $this->_categoryHelper->getStoreCategories();


                              public function getCategory($categoryId)

                              return $this->_categoryRepository->get($categoryId);



                              Code for your template file:



                              $categories = $block->getStoreCategories();
                              foreach ($categories as $category)
                              echo $category->getName();
                              echo ' ( ' . $category->getProductCount() . ' )';

                              $subCategories = $block->getCategory($category->getId());
                              foreach ($subCategories as $subCategory)
                              echo $subCategory->getName();
                              echo ' ( ' . $subCategory->getProductCount() . ' )';




                              Source: Magento 2: Get parent category, children categories & product count







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Sep 16 '16 at 6:49

























                              answered Sep 16 '16 at 5:43









                              Mukesh ChapagainMukesh Chapagain

                              3,82812243




                              3,82812243





















                                  1














                                  I solved it as below,



                                  protected $_category;
                                  protected $_productCollection;

                                  /** You should provide your root category here, and it will return comma seperated sub category list */
                                  public function getChildren($categoryId = false)

                                  if ($this->_category)
                                  return $this->_category->getChildren();
                                  else
                                  return $this->getCategory($categoryId)->getChildren();



                                  protected function _getProductCollection()

                                  $childListStr = $this->getChildren( 2 ); // Provide the root category ID
                                  $childList = explode( ",", $childListStr );
                                  $catToLoad = array();

                                  foreach( $childList as $item )
                                  array_push( $catToLoad, $item );


                                  if ($this->_productCollection === null)
                                  $layer = $this->getLayer();
                                  $this->_productCollection = $layer->getProductCollection();


                                  $this->_productCollection->addCategoriesFilter(['in' => $catToLoad ]);
                                  return $this->_productCollection;






                                  share|improve this answer



























                                    1














                                    I solved it as below,



                                    protected $_category;
                                    protected $_productCollection;

                                    /** You should provide your root category here, and it will return comma seperated sub category list */
                                    public function getChildren($categoryId = false)

                                    if ($this->_category)
                                    return $this->_category->getChildren();
                                    else
                                    return $this->getCategory($categoryId)->getChildren();



                                    protected function _getProductCollection()

                                    $childListStr = $this->getChildren( 2 ); // Provide the root category ID
                                    $childList = explode( ",", $childListStr );
                                    $catToLoad = array();

                                    foreach( $childList as $item )
                                    array_push( $catToLoad, $item );


                                    if ($this->_productCollection === null)
                                    $layer = $this->getLayer();
                                    $this->_productCollection = $layer->getProductCollection();


                                    $this->_productCollection->addCategoriesFilter(['in' => $catToLoad ]);
                                    return $this->_productCollection;






                                    share|improve this answer

























                                      1












                                      1








                                      1







                                      I solved it as below,



                                      protected $_category;
                                      protected $_productCollection;

                                      /** You should provide your root category here, and it will return comma seperated sub category list */
                                      public function getChildren($categoryId = false)

                                      if ($this->_category)
                                      return $this->_category->getChildren();
                                      else
                                      return $this->getCategory($categoryId)->getChildren();



                                      protected function _getProductCollection()

                                      $childListStr = $this->getChildren( 2 ); // Provide the root category ID
                                      $childList = explode( ",", $childListStr );
                                      $catToLoad = array();

                                      foreach( $childList as $item )
                                      array_push( $catToLoad, $item );


                                      if ($this->_productCollection === null)
                                      $layer = $this->getLayer();
                                      $this->_productCollection = $layer->getProductCollection();


                                      $this->_productCollection->addCategoriesFilter(['in' => $catToLoad ]);
                                      return $this->_productCollection;






                                      share|improve this answer













                                      I solved it as below,



                                      protected $_category;
                                      protected $_productCollection;

                                      /** You should provide your root category here, and it will return comma seperated sub category list */
                                      public function getChildren($categoryId = false)

                                      if ($this->_category)
                                      return $this->_category->getChildren();
                                      else
                                      return $this->getCategory($categoryId)->getChildren();



                                      protected function _getProductCollection()

                                      $childListStr = $this->getChildren( 2 ); // Provide the root category ID
                                      $childList = explode( ",", $childListStr );
                                      $catToLoad = array();

                                      foreach( $childList as $item )
                                      array_push( $catToLoad, $item );


                                      if ($this->_productCollection === null)
                                      $layer = $this->getLayer();
                                      $this->_productCollection = $layer->getProductCollection();


                                      $this->_productCollection->addCategoriesFilter(['in' => $catToLoad ]);
                                      return $this->_productCollection;







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Sep 16 '16 at 7:39









                                      nuwausnuwaus

                                      91931945




                                      91931945





















                                          0














                                          Hi I have another way to get product collection from root category... check it out.. I hope this help



                                          public function __construct(
                                          MagentoCatalogModelLayerCategory $categoryLayer
                                          )
                                          $this->_categoryLayer = $categoryLayer;


                                          public function getProductCollection($category)
                                          return $this->_categoryLayer->setCurrentCategory($category)->getProductCollection();






                                          share|improve this answer



























                                            0














                                            Hi I have another way to get product collection from root category... check it out.. I hope this help



                                            public function __construct(
                                            MagentoCatalogModelLayerCategory $categoryLayer
                                            )
                                            $this->_categoryLayer = $categoryLayer;


                                            public function getProductCollection($category)
                                            return $this->_categoryLayer->setCurrentCategory($category)->getProductCollection();






                                            share|improve this answer

























                                              0












                                              0








                                              0







                                              Hi I have another way to get product collection from root category... check it out.. I hope this help



                                              public function __construct(
                                              MagentoCatalogModelLayerCategory $categoryLayer
                                              )
                                              $this->_categoryLayer = $categoryLayer;


                                              public function getProductCollection($category)
                                              return $this->_categoryLayer->setCurrentCategory($category)->getProductCollection();






                                              share|improve this answer













                                              Hi I have another way to get product collection from root category... check it out.. I hope this help



                                              public function __construct(
                                              MagentoCatalogModelLayerCategory $categoryLayer
                                              )
                                              $this->_categoryLayer = $categoryLayer;


                                              public function getProductCollection($category)
                                              return $this->_categoryLayer->setCurrentCategory($category)->getProductCollection();







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 1 '16 at 7:57









                                              HoangHieuHoangHieu

                                              746514




                                              746514





















                                                  -4














                                                  Try this



                                                   $category = Mage::getModel('catalog/category')->load(2);
                                                  $children = Mage::getModel('catalog/category')->getCollection()->setStoreId(Mage::app()->getStore()->getId());
                                                  $children->addAttributeToSelect('*')
                                                  ->addAttributeToFilter('parent_id', $category->getId())
                                                  ->addAttributeToFilter('is_active', 1)
                                                  ->addAttributeToSort('position');
                                                  foreach($children as $child)


                                                  $category=Mage::getModel('catalog/category')->load($child->entity_id);






                                                  share|improve this answer




















                                                  • 3





                                                    This is Magento 1 way.

                                                    – Khoa TruongDinh
                                                    Sep 15 '16 at 13:29















                                                  -4














                                                  Try this



                                                   $category = Mage::getModel('catalog/category')->load(2);
                                                  $children = Mage::getModel('catalog/category')->getCollection()->setStoreId(Mage::app()->getStore()->getId());
                                                  $children->addAttributeToSelect('*')
                                                  ->addAttributeToFilter('parent_id', $category->getId())
                                                  ->addAttributeToFilter('is_active', 1)
                                                  ->addAttributeToSort('position');
                                                  foreach($children as $child)


                                                  $category=Mage::getModel('catalog/category')->load($child->entity_id);






                                                  share|improve this answer




















                                                  • 3





                                                    This is Magento 1 way.

                                                    – Khoa TruongDinh
                                                    Sep 15 '16 at 13:29













                                                  -4












                                                  -4








                                                  -4







                                                  Try this



                                                   $category = Mage::getModel('catalog/category')->load(2);
                                                  $children = Mage::getModel('catalog/category')->getCollection()->setStoreId(Mage::app()->getStore()->getId());
                                                  $children->addAttributeToSelect('*')
                                                  ->addAttributeToFilter('parent_id', $category->getId())
                                                  ->addAttributeToFilter('is_active', 1)
                                                  ->addAttributeToSort('position');
                                                  foreach($children as $child)


                                                  $category=Mage::getModel('catalog/category')->load($child->entity_id);






                                                  share|improve this answer















                                                  Try this



                                                   $category = Mage::getModel('catalog/category')->load(2);
                                                  $children = Mage::getModel('catalog/category')->getCollection()->setStoreId(Mage::app()->getStore()->getId());
                                                  $children->addAttributeToSelect('*')
                                                  ->addAttributeToFilter('parent_id', $category->getId())
                                                  ->addAttributeToFilter('is_active', 1)
                                                  ->addAttributeToSort('position');
                                                  foreach($children as $child)


                                                  $category=Mage::getModel('catalog/category')->load($child->entity_id);







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Sep 16 '16 at 7:25









                                                  Murtuza Zabuawala

                                                  12.6k73362




                                                  12.6k73362










                                                  answered Sep 15 '16 at 13:13









                                                  Ravi ThankiRavi Thanki

                                                  34429




                                                  34429







                                                  • 3





                                                    This is Magento 1 way.

                                                    – Khoa TruongDinh
                                                    Sep 15 '16 at 13:29












                                                  • 3





                                                    This is Magento 1 way.

                                                    – Khoa TruongDinh
                                                    Sep 15 '16 at 13:29







                                                  3




                                                  3





                                                  This is Magento 1 way.

                                                  – Khoa TruongDinh
                                                  Sep 15 '16 at 13:29





                                                  This is Magento 1 way.

                                                  – Khoa TruongDinh
                                                  Sep 15 '16 at 13:29

















                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Magento Stack Exchange!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f136517%2fget-product-collection-by-root-category-and-all-its-subcategories-in-magento-2%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Magento 2 - Add success message with knockout Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Success / Error message on ajax request$.widget is not a function when loading a homepage after add custom jQuery on custom themeHow can bind jQuery to current document in Magento 2 When template load by ajaxRedirect page using plugin in Magento 2Magento 2 - Update quantity and totals of cart page without page reload?Magento 2: Quote data not loaded on knockout checkoutMagento 2 : I need to change add to cart success message after adding product into cart through pluginMagento 2.2.5 How to add additional products to cart from new checkout step?Magento 2 Add error/success message with knockoutCan't validate Post Code on checkout page

                                                  Fil:Tokke komm.svg

                                                  Where did Arya get these scars? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why did Arya refuse to end it?Has the pronunciation of Arya Stark's name changed?Has Arya forgiven people?Why did Arya Stark lose her vision?Why can Arya still use the faces?Has the Narrow Sea become narrower?Does Arya Stark know how to make poisons outside of the House of Black and White?Why did Nymeria leave Arya?Why did Arya not kill the Lannister soldiers she encountered in the Riverlands?What is the current canonical age of Sansa, Bran and Arya Stark?