How to call category collection on homepage in Magento 2?

In this blog, we are going to confer about how to call category collection on the homepage in Magento 2.

Attract online shoppers and drive sales with our Magento eCommerce solution, click here and get started!!!

How to call category collection on the homepage in Magento 2?

Here I will explain to you the following steps:

Step 1: form you latest extension for our case in folder app/code/Webnexs/CategoriesSide

The following example for module.xml :

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

<module name="Webnexs_CategoriesSide" setup_version="1.0.0" schema_version="1.0.0">

<sequence>

<module name="Magento_Catalog"/>

</sequence>

</module>

</config>

For di.xml :

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Webnexs\CategoriesSide\Block\CategorisCollection">
<arguments>
<argument name="deleteorderAction" xsi:type="array">
<item name="context" xsi:type="string">\Magento\Framework\View\Element\Template\Context</item>
<item name="helper" xsi:type="string">\Magento\Catalog\Helper\Category</item>
<item name="flatstate" xsi:type="string">\Magento\Catalog\Model\Indexer\Category\Flat\State</item>
<item name="menu" xsi:type="string">\Magento\Theme\Block\Html\Topmenu</item>
</argument>
</arguments>
</type>
</config>

Note: Here the power is for inject the class  \Magento\Catalog\Helper\Category for getting all categories of the present store (And OR) obtain the top menu HTML for the entire collection you require to inject \Magento\Theme\Block\Html\Topmenu

Step 2: The insertion is for our data source the block
Webnexs\CategoriesSide\Block\CategorisCollection build and put the code:

<?php
namespace Webnexs\CategoriesSide\Block;
class CategorisCollection extends \Magento\Framework\View\Element\Template
{
protected $_categoryHelper;
protected $categoryFlatConfig;
protected $topMenu;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Helper\Category $categoryHelper
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Helper\Category $categoryHelper,
\Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
\Magento\Theme\Block\Html\Topmenu $topMenu
) {
$this->_categoryHelper = $categoryHelper;
$this->categoryFlatConfig = $categoryFlatState;
$this->topMenu = $topMenu;
parent::__construct($context);
}
/**
* Return categories helper
*/ 
public function getCategoryHelper()
{
return $this->_categoryHelper;
}
/**
* Return top menu html
* getHtml($outermostClass = '', $childrenWrapClass = '', $limit = 0)
* example getHtml('level-top', 'submenu', 0)
*/ 
public function getHtml()
{
return $this->topMenu->getHtml();
}
/**
* Retrieve current store categories
*
* @param bool|string $sorted
* @param bool $asCollection
* @param bool $toLoad
* @return \Magento\Framework\Data\Tree\Node\Collection|\Magento\Catalog\Model\Resource\Category\Collection|array
*/ 
public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
}
/**
* Retrieve child store categories
*
*/ 
public function getChildCategories($category)
{
if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
$subcategories = (array)$category->getChildrenNodes();
} else {
$subcategories = $category->getChildren();
}
return $subcategories;
}
}

Note:  Here the main key is  getStoreCategories and get  Child Categories ($category)
, it will find you the data collection tree from helper , and getHtml()  it will return the complete collection is more fast for correct the html

Step 3 – Now form your template inside view/frontend/template/storecategories.phtml with content :

<?php
$categories = $this->getStoreCategories(true,false,true);
$categoryHelper = $this->getCategoryHelper();
?>
<ul>
<?php
foreach($categories as $category):
if (!$category->getIsActive()) {
continue;
}
?>
<li><a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>"><?php echo $category->getName() ?></a></li>
<?php 
if($childrenCategories = $this->getChildCategories($category)):
?>
<ul>
<?php
foreach($childrenCategories as $childrenCategory):
if (!$childrenCategory->getIsActive()) {
continue;
}
?>
<li><a href="<?php echo $categoryHelper->getCategoryUrl($childrenCategory) ?>"><?php echo $childrenCategory->getName() ?></a></li>
<?php
endforeach;
?>
</ul>
<?php
endif;
endforeach;
?>
</ul>
<h1>OR Just</h1>
<?php echo $this->getHtml() ?>

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

Step 4: At present, you have 2 techniques for include the left or right container:

  • In admin panel go to the homepage to home page select content choose the page and on the edit action now select tab design select 2 columns with let bar from layout and place  within the Layout Update XML :
<referenceContainer name="sidebar.main">
 <block class="Webnexs\CategoriesSide\Block\CategorisCollection" name="categoriecollection" template="Webnexs_CategoriesSide::storecategories.phtml"/>
 </referenceContainer>
  • Create XML inside view/frontend/layout/ and put the code :
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
 <body>
 <referenceContainer name="sidebar.main">
 <block class="Webnexs\CategoriesSide\Block\CategorisCollection" name="categoriecollection" template="Webnexs_CategoriesSide::storecategories.phtml"/>
 </referenceContainer>
 </body>
</page>

I hope, the above-mentioned steps show you how to call category collection on the homepage in Magento 2.

How to call category collection on homepage in Magento 2?

Last Update: March 3, 2021  

February 20, 2018   1108   Nandini Ramachandran    Magento 2 Tutorial, Magento2    
Total 2 Votes:
1

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn