0

enter image description hereHow can I display all sub-categories above the product list on the category page?

2 Answers 2

1

I won't recommend using objectmanager. Instead, create Block and call the function.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
$subcats = $category->getChildrenCategories();
?>
<div class="row">
    <?php
    foreach ($subcats as $subcat) {
        if ($subcat->getIsActive()) {

            $subcat_url = $subcat->getUrl();
            $subcat_img = "";
            $placeholder_img = "/media/placeholder.png";
            $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId()); 
            ?>
            <div class="col-sm-6 sub-cat-tile">
                <a href="<?php echo $subcat_url; ?>">
                    <img src="<?php echo $subcategory->getImageUrl() ? $subcat_img : $placeholder_img; ?>">
                    <p><?php echo $subcat->getName(); ?></p>
                </a>

            </div>
            <?php
        }
    } ?>
</div>
2
  • How can I apply this to every category page? I am new in magento (sorry if the question is stupid).
    – glafche
    Aug 14, 2018 at 14:29
  • app\design\frontend\Vendor\theme\Magento_Catalog\templates\product\list.phtml Aug 14, 2018 at 14:31
0

Create a block file in your custom module and write the code like below:

protected $categoryRepository;

public function __construct(
    \Magento\Catalog\Model\CategoryRepository $categoryRepository
) {
    $this->categoryRepository = $categoryRepository;
}

Now create a function and write something like the following:

$parent_category_id = 3;
$categoryObj = $this->categoryRepository->get($parent_category_id);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $subcategorie) {
    echo '    --> '.$subcategorie->getName().'
';
}

I have assumed that you can get the current category in category page using registry object.

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