1

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>
2

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() . ' )';
    }
  }
?> 
  • I have tried this but not working for me. Do you have any idea? – Siva Sep 24 at 9:52
  • 1
    Now it is working. Rename Block file and Class name from CategoriesList To Categorylist and changes code as per latest changes on block and tempate files. – Rajesh Hothi Sep 24 at 11:34
  • I will try.. Is there any reason for putting the file name as Categorylist? – Siva Sep 24 at 11:50
  • Thanks. It's working now. But both the parent and sub categories shows in same line. How to show it as a list. Please look into the question for my code – Siva Sep 24 at 12:43
  • 1
    Please bind code in phtml template with <u><li> html tag like <ul class="clearfix"><li>parent Category <ul class="child-cat"><li>child Category</li></u></li></u> – Rajesh Hothi Sep 24 at 13:09
1

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); 
  • Thanks. But we should not use object manager concept right? – Siva Sep 24 at 5:06
  • Yes, we also create the object using a constructor for the above solution. – Chirag Gondaliya Sep 24 at 5:19
  • I have uploaded the code I'm using. As of now, what I have done is I have followed the link in the question and getting parent categories by using the code I pasted. Now, how can I load sub category? – Siva Sep 24 at 5:50
  • I have used the code you suggested and it works but how can I use this on the code I have pasted in the question – Siva Sep 24 at 5:50
  • Can you please help me? – Siva Sep 24 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.