Question

I have installed Magento2.3.2 EE on local. I have seen that the default category menu is not working correctly so that we want to load category and subcategory collection at top menu position with our own design.

I have successfully got the parent category by referring the below link:

http://www.blogtreat.com/how-to-get-category-collection-in-magento-2/

But I need to show the subcategory as well. How to do that?

Can anyone please help me its urgent task for me?

Code:

 <?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php
/**
 * Top menu for store
 *
 * @var $block \Magento\Theme\Block\Html\Topmenu
 */
?>


<!-- <div class="sections nav-sections">
      <div class="menu">
      <span>1</span>
      <span>1</span>
      <span>1</span>
    </div> -->
    <link rel="stylesheet" type="text/css" href="<?php echo $block->getViewFileUrl('css/cart.css')?>">
<header class="headers">
  <div class="header-inrs">
    <div class="menu-container">
  <div class="menus">

    <ul class="clearfix">
      <?php
      $categories = $block->getStoreCategories();

foreach ($categories as $category):


  ?>  


      <li><a href="<?php echo $category->getRequestPath();?>"><?php echo $category->getName(); ?></a></li>
      <?php 

      $subCategories = $block->getCategoryById($category->getId());
      foreach ($subCategories->getChildrenCategories() as $subCategory):
        ?>

      <li><a href="#"><?php echo $subCategory->getName(); ?></a>
            <ul>
              <li><a href="#"></a></li>
            </ul>
          </li>
      <?php endforeach; ?>
    <?php endforeach; ?>
      <!-- <li><a href="#">TV/ AUDIO/ VIDEO  <i class="fa fa-angle-down" aria-hidden="true"></i></a>
        <ul>
          <li><a href="#">School</a>
            <ul>
              <li><a href="#">Lidership</a></li>
              <li><a href="#">History</a></li>
              <li><a href="#">Locations</a></li>
              <li><a href="#">Careers</a></li>
            </ul>
          </li>
          <li><a href="#">Study</a>
            <ul>
              <li><a href="#">Undergraduate</a></li>
              <li><a href="#">Masters</a></li>
              <li><a href="#">International</a></li>
              <li><a href="#">Online</a></li>
            </ul>
          </li>
          <li><a href="#">Research</a>
            <ul>
              <li><a href="#">Undergraduate research</a></li>
              <li><a href="#">Masters research</a></li>
              <li><a href="#">Funding</a></li>
            </ul>
          </li>
          <li><a href="#">Something</a>
            <ul>
              <li><img src="https://placeimg.com/300/200/nature"></li>
            </ul>
          </li>
        </ul>
      </li>
      <li><a href="#">MOBILE <i class="fa fa-angle-down" aria-hidden="true"></i></a>
        <ul>
          <li><a href="#">Today</a></li>
          <li><a href="#">Calendar</a></li>
          <li><a href="#">Sport</a></li>
        </ul>
      </li>
      <li><a href="#">COMPUTER APPLIANCE  <i class="fa fa-angle-down" aria-hidden="true"></i></a>
        <ul>
          <li><a href="#">School</a>
            <ul>
              <li><a href="#">Lidership</a></li>
              <li><a href="#">History</a></li>
              <li><a href="#">Locations</a></li>
              <li><a href="#">Careers</a></li>
            </ul>
          </li>
          <li><a href="#">Study</a>
            <ul>
              <li><a href="#">Undergraduate</a></li>
              <li><a href="#">Masters</a></li>
              <li><a href="#">International</a></li>
              <li><a href="#">Online</a></li>
            </ul>
          </li>
          <li><a href="#">Study</a>
            <ul>
              <li><a href="#">Undergraduate</a></li>
              <li><a href="#">Masters</a></li>
              <li><a href="#">International</a></li>
              <li><a href="#">Online</a></li>
            </ul>
          </li>
          <li><a href="#">Empty sub</a>
            <ul>
              <li><img src="https://blog.malwarebytes.com/wp-content/uploads/2017/07/shutterstock_328174601-900x506.jpg"></li>
            </ul>
          </li>
        </ul>
      </li>
      <li><a href="#">AIR CONDITIONER</a></li>
      <li><a href="#">SUPPORT</a></li> -->
    </ul>
  </div>
</div>
</div>

<div class="search-outer">
    <div class="search-icon">
      <span></span>
    </div>
    <div class="wishlist">
      <span class="wishlist-icon"></span>
    </div>
    <div class="my-account">
      <span class="my-account"></span>
    </div>
    <div class="cart">
      <span class="cart-icon"></span>
    </div>
  </div>
  </div>
</header>



</div>
Was it helpful?

Solution

1.Create a Custom Block Class in file name Categorylist.php

PackageName\moduleName\Block\Categorylist.php

Add below code

<?php
namespace PackageName\moduleName\Block;
class Categorylist extends \Magento\Framework\View\Element\Template
{    
    protected $_categoryHelper;
    protected $categoryFactory;
    protected $_catalogLayer;
    protected $_categoryRepository;


    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,     
        \Magento\Catalog\Helper\Category $categoryHelper,        
    \Magento\Catalog\Model\CategoryRepository $categoryRepository,        

        array $data = []
    ) {


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


    }

    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }

    public function getCategoryById($categoryId) 
    {
        return $this->_categoryRepository->get($categoryId);

    }


}

2.Inside your phtm templte add below code

<?php

// Get Store Categories Collection 
$categorys = $block->getStoreCategories(false,false,true);
 foreach($categorys as $category){
     echo $category->getName();

    $subCategories = $block->getCategoryById($category->getId());

    foreach ($subCategories->getChildrenCategories() as $subCategory) {
        echo $subCategory->getName();
        echo ' ( ' . $subCategory->getProductCount() . ' )';
    }
  }
?> 

OTHER TIPS

Please try this to get a solution

<?php

function categoryLoop($id){
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $categories = $objectManager->create('Magento\Catalog\Model\Category')->load($id);

    if($categories->hasChildren()){
    echo "<ul>";
        $subcategories = explode(',', $categories->getChildren());
        foreach ($subcategories as $category) {
            $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
            echo "<li>";
            echo $subcategory->getName();
            echo "</li>";
            //echo "<br>";
            if($subcategory->hasChildren()){ categoryLoop($category); }
        }
    echo "</ul>";
    }
}

categoryLoop(2); 
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top