0

I want to get a list of a parent categories sub-categories, their name, link and image. An example of what I require is below.

I know this can be done using object manager but I understand that is not recommended.

I need to be able to call this in a CMS static block, so I can apply it only in specific categories I choose.

CURRENT CODE (results in a blank page)

    <?php 
        //If there are sub categories
        $categories = $block->getCurrentChildCategories();
        $categoriescount = $block->getCurrentChildCategories()->count();
        if ($categoriescount > 0):  ?>
        <div class="container_12">  
        <?php 
            //Loop through categories
            foreach ($categories as $category): ?>
            <div class="grid_3 alpha special-spacing" style="margin-bottom:10px;">
                <div>
                    <!--<p class="cat-link"><?php echo $category->getName()?></p>-->
                    <a href="<?php echo $block->getCategoryUrl($category) ?>" class="cat-link"><?php echo $category->getName()?></a>
                </div>
                <?php //get category products
                $categoryProducts = $category->getProductCollection();
                   if(count($categoryProducts) <> 1):?>
                <a href="<?php echo $block->getCategoryUrl($category)?>" class="cat-image">
                <?php else:?>
                <?php $product = $categoryProducts->getFirstItem();?>
                <a href="<?php echo $product->getProductUrl()?>" class="cat-image">
                <?php endif;?>
                </a>
            </div>

            <?php endforeach; ?>
        <div class="clear"></div>
        </div>
        <?php else:?>
<h3>product not found...</h3>
<?php endif;?>

DESIRED RESULT

Category Listing Example

  • Which block type you are using for this template ? – Kishan Patadia May 28 '17 at 12:30
  • Is what you mean Kishan... {{block class="Magento\Catalog\Block\Category\View" template="Magento_Theme::html/mycategoryblock.phtml"}} – YorkieMagento May 28 '17 at 13:17
  • Did you achieved this? Please share answer here. – Pallavi Nov 9 '18 at 7:57

Your Answer

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

Browse other questions tagged or ask your own question.