Magento – Magento 2: Display list of specific categories on Home Page

categoryfrontendhomemagento-2.1magento2

I need to show 6 specific categories on my Magento home page. I have the category ids with me. I want to display both the category image and name of that specific category. I have created a category.phtml and have the following code in this file.

<?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; ?>

And called this phtml in cms home page as:

{{block class="Magento\Framework\View\Element\Template" template="Vendor_Theme::category.phtml"}}

But it is showing only the root categories. Please help.

Best Answer

Better idea create a custom module for this.

This module must have below files:

  • app\code\[VendorName]\[ModuleName]\composer.json
  • app\code\[VendorName]\[ModuleName]\registration.php
  • app\code\[VendorName]\[ModuleName]\etc\module.xml
  • app\code\[VendorName]\[ModuleName]\Block\Categories.php

On block class, you should create category collection filter and filter that collection by your 6 category ids

<?php
namespace [VendorName]\[ModuleName]\Block;
class Categories extends \Magento\Framework\View\Element\Template
{

  protected $_categoryCollectionFactory;
  protected $_categoryHelper;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Helper\Category $categoryHelper,
        array $data = []
    )
    {
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryHelper = $categoryHelper;
        parent::__construct($context, $data);
    }

    public function getCategories()
    {
        $collection = $this->_categoryCollectionFactory->create();
        $categoryIds = array(CatId1,CatId2,...CatId6);
        $collection->addAttributeToFilter('entity_id',array('in',$categoryIds));
        return $collection
    }
  }

Then use this new block instead of Magento\Framework\View\Element\Template.

See idea how use block class at http://blog.chapagain.com.np/magento-2-get-list-of-all-categories-store-categories/

Related Topic