/   /   /  Magento 2 Frontend : How to call category collection on home page

Note:

For more extensions and themes visit our store

Magento 2 Frontend : How to call category collection on home page


Wow this tutorial observe the frontend side of Magento 2 , how you can get collection of categories in the home page , for that we create small extension , and we explain here :
You can download the complete code from github
1 – Create you new Extension for our case in folder app/code/Ibnab/CategoriesSide
and inside etc folder declare you etc declare module.xml and di.xml with content :
module.xml :

  1.  
  2. <?xml version="1.0"?>
  3. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
  4.     <module name="Ibnab_CategoriesSide" setup_version="1.0.0" schema_version="1.0.0">
  5.         <sequence>
  6.             <module name="Magento_Catalog"/>
  7.         </sequence>
  8.     </module>
  9. </config>
  10.  

di.xml :
  1.  
  2. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
  3.     <type name="Ibnab\CategoriesSide\Block\CategorisCollection">
  4.         <arguments>
  5.             <argument name="deleteorderAction" xsi:type="array">
  6.                 <item name="context" xsi:type="string">\Magento\Framework\View\Element\Template\Context</item>
  7.                 <item name="helper" xsi:type="string">\Magento\Catalog\Helper\Category</item>
  8.                 <item name="flatstate" xsi:type="string">\Magento\Catalog\Model\Indexer\Category\Flat\State</item>
  9.                <item name="menu" xsi:type="string">\Magento\Theme\Block\Html\Topmenu</item>
  10.             </argument>
  11.         </arguments>
  12.     </type>
  13. </config>
  14.  

Note - Here the dependency is for inject the class  \Magento\Catalog\Helper\Category for getting all categories of current store (And OR ) get the top menu html for the complete collection you need inject \Magento\Theme\Block\Html\Topmenu  ,

2 -  the injection is for our data source the block
Ibnab\CategoriesSide\Block\CategorisCollection create and put the code :

  1.  
  2. <?php
  3. namespace Ibnab\CategoriesSide\Block;
  4. class CategorisCollection extends \Magento\Framework\View\Element\Template
  5. {
  6.      protected $_categoryHelper;
  7.      protected $categoryFlatConfig;
  8.      protected $topMenu;
  9.     /**
  10.      * @param \Magento\Framework\View\Element\Template\Context $context
  11.      * @param \Magento\Catalog\Helper\Category $categoryHelper
  12.      * @param array $data
  13.      */
  14.     public function __construct(
  15.         \Magento\Framework\View\Element\Template\Context $context,
  16.         \Magento\Catalog\Helper\Category $categoryHelper,
  17.         \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
  18.         \Magento\Theme\Block\Html\Topmenu $topMenu
  19.     ) {
  20.         $this->_categoryHelper = $categoryHelper;
  21.         $this->categoryFlatConfig = $categoryFlatState;
  22.         $this->topMenu = $topMenu;
  23.         parent::__construct($context);
  24.     }
  25.     /**
  26.      * Return categories helper
  27.      */   
  28.     public function getCategoryHelper()
  29.     {
  30.         return $this->_categoryHelper;
  31.     }
  32.     /**
  33.      * Return top menu html
  34.      * getHtml($outermostClass = '', $childrenWrapClass = '', $limit = 0)
  35.      * example getHtml('level-top', 'submenu', 0)
  36.      */   
  37.     public function getHtml()
  38.     {
  39.         return $this->topMenu->getHtml();
  40.     }
  41.     /**
  42.      * Retrieve current store categories
  43.      *
  44.      * @param bool|string $sorted
  45.      * @param bool $asCollection
  46.      * @param bool $toLoad
  47.      * @return \Magento\Framework\Data\Tree\Node\Collection|\Magento\Catalog\Model\Resource\Category\Collection|array
  48.      */    
  49.    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
  50.     {
  51.         return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
  52.     }
  53.     /**
  54.      * Retrieve child store categories
  55.      *
  56.      */ 
  57.     public function getChildCategories($category)
  58.     {
  59.            if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
  60.                 $subcategories = (array)$category->getChildrenNodes();
  61.             } else {
  62.                 $subcategories = $category->getChildren();
  63.             }
  64.             return $subcategories;
  65.     }
  66. }
  67.  

Note – The more important here is  getStoreCategories and getChildCategories($category)
  , it  get you the data collection tree from helper , and getHtml()
 is return the complete collection is more quick for correct the html

3 - ok now create you template inside view/frontend/template/storecategories.phtml with content :

  1.  
  2. <?php
  3. $categories = $this->getStoreCategories(true,false,true);
  4. $categoryHelper = $this->getCategoryHelper();
  5. ?>
  6. <ul>
  7. <?php
  8. foreach($categories as $category):
  9.      if (!$category->getIsActive()) {
  10.         continue;
  11.      }
  12. ?>
  13. <li><a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>"><?php echo $category->getName() ?></a></li>
  14. <?php  
  15. if($childrenCategories = $this->getChildCategories($category)):
  16. ?>
  17. <ul>
  18. <?php
  19. foreach($childrenCategories as $childrenCategory):
  20.      if (!$childrenCategory->getIsActive()) {
  21.         continue;
  22.      }
  23. ?>
  24. <li><a href="<?php echo $categoryHelper->getCategoryUrl($childrenCategory) ?>"><?php echo $childrenCategory->getName() ?></a></li>
  25. <?php
  26. endforeach;
  27. ?>
  28. </ul>
  29. <?php
  30. endif;
  31. endforeach;
  32. ?>
  33. </ul>
  34. <h1>OR Just</h1>
  35. <?php echo $this->getHtml() ?>
  36.  

Note : if you have just 2 level or less you can play but if you have many child why not using $this->getHtml()

4 – Now you have 2 technique for add to left or right container :
   A – first technique go to you home page in the admin panel  click content choose page and on the edit action now click tab design choose 2 columns with let bar from layout and put  inside the Layout Update XML :

  1.  
  2.         <referenceContainer name="sidebar.main">
  3.             <block class="Ibnab\CategoriesSide\Block\CategorisCollection" name="categoriecollection" template="Ibnab_CategoriesSide::storecategories.phtml"/>
  4.         </referenceContainer>
  5.  

  B – the second technique is to create cms_index_index.xml inside view/frontend/layout/ and put the code : 
  1.  
  2. <?xml version="1.0"?>
  3. <!--
  4. /**
  5.  * Copyright © 2015 Magento. All rights reserved.
  6.  * See COPYING.txt for license details.
  7.  */
  8. -->
  9. <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
  10.     <body>
  11.         <referenceContainer name="sidebar.main">
  12.             <block class="Ibnab\CategoriesSide\Block\CategorisCollection" name="categoriecollection" template="Ibnab_CategoriesSide::storecategories.phtml"/>
  13.         </referenceContainer>
  14.     </body>
  15. </page>
  16.  

You can download the complete code from github

Comments

Related Posts

make your store more efficient

Solving problems. With open source technology. Professional results. That’s what makes Ibnab your best choice

IBNAB is a company made of a group of professionals whose work is providing secure open source solutions. Our company strives for reaching magnificent results with each experience and provides professional open source solutions that cover every part of the business process.