0

I am trying to display certain categories along with their images on homepage. I've made sure the categories dont appear in the top menu and only in the code that I am trying to use. Below code only displays category which are in TopMenu.

Is there a way around?

<?php 
  $categoryHelper = $this->helper('Magento\Catalog\Helper\Category');
  foreach($categoryHelper->getStoreCategories() as $category): 
?>
   <li>
     <a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>">
       <?php echo $category->getName() ?>
     </a>
   </li>
<?php endforeach; ?>
  • do you want show all categories whether in menu or not – Sourav Apr 6 '18 at 3:03
0

Please try this code, you can optimized it as you wish.

<?php 

$categoryHelper = $this->helper('Magento\Catalog\Helper\Category');
$objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()
->addAttributeToFilter("parent_id",2)
->addAttributeToFilter("is_active",1)
->addAttributeToFilter("include_in_menu",0)
->addAttributeToSelect('*'); 

foreach($categories as $category): 
?>
    <li>
        <a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>">
            <?php echo $category->getName() ?>
        </a>
    </li>
<?php endforeach; ?>
  • It is necessary to follow the code patterns while doing development on Magento 2. Magento Community recommends using Magento 2 Dependency Injection rather than ObjectManager. It is still used somewhere in the core of Magento 2, but it will get refactored soon. So, the best recommendation is, DO NOT USE THE OBJECTMANAGER. It is a good practice to know what the code depends on, rather than having hidden dependencies in the middle of the code. That is why Magento 2 Dependency Injection is preferred by the structure. – Sourav Apr 6 '18 at 3:20
  • Yes sure, you need to adapt this in the code. It is not good way to use the objectMsnager. But I don’t know the full code. But the main idea is the way of getting the categories that you need. – WISAM HAKIM Apr 6 '18 at 3:32

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.