3 Comments

Getting Sub Category Images in Magento2

Custom theme reuse Lumas start page
How to display HTML from uiComponent returning JSON

I am trying to get at Category Images from within Magento_Catalogtemplatenavigationleft.phtml. This file shows a list of sub-categories.

This is that file:

<?php if (!$block->getCategory()) {
    return;
} ?>
<?php $_categories = $block->getCurrentChildCategories(); ?>
<?php $_count = is_array($_categories) ? count($_categories) : $_categories->count(); ?>
<?php if ($_count): ?>
    <div class="block filter">
        <div class="title">
            <strong><?php /* @escapeNotVerified */ echo __('Shop By') ?></strong>
        </div>
        <div class="content">
            <strong class="subtitle"><?php /* @escapeNotVerified */ echo __('Shopping Options') ?></strong>
            <dl class="options" id="narrow-by-list2">
                <dt><?php /* @escapeNotVerified */ echo __('Category') ?></dt>
                <dd>
                    <ol class="items">
                        <?php foreach ($_categories as $_category): ?>
                            <?php if ($_category->getIsActive()): ?>
                                <li class="item">
                                    <a href="<?php /* @escapeNotVerified */ echo $block->getCategoryUrl($_category) ?>"<?php if ($block->isCategoryActive($_category)): ?> class="current"<?php endif; ?>>
                                        <img src="<?php echo $block->getCategory($_category)->getImageUrl(); ?>">
                                        <p><?php echo $block->escapeHtml($_category->getName()) ?></p>
                                    </a>
                                    <span class="count"><?php /* @escapeNotVerified */ echo $_category->getProductCount() ?></span>
                                </li>
                            <?php endif; ?>
                        <?php endforeach ?>
                    </ol>
                </dd>
            </dl>
        </div>
    </div>
<?php endif; ?>

The line I was hoping would work is:

$block->getCategory($_category)->getImageUrl();

However this is returning the image for the current category, not the sub-categories.

Can anyone point me in the right direction?

Related Posts

  • Magento 2 – show category tree in left navigation (1)
    Is there a way to get category tree list and limit the depth of it on the Magento 2 main category left sidebar subcategories list? Currently the list goes like this: Categories: - Subcategory 1 - Subcategory 2 - Subcategory 3 - Subcategory 4 ... The file which generates this list […]
  • How get all subcategories of specific category? (3)
    I have a file left.phtml for a vertical menu. I want to get all subcategories of specific category ID3. I have this code. <?php if (!Mage::registry('current_category')) return ?> <?php $categoryId = 3; $category = […]
  • Magento Fatal error – Call to a member function count (1)
    I wish to copy this content : appdesignfrontendbasedefaulttemplatecatalognavigationleft.phtl <?php if (!Mage::registry('current_category')) return ?> <?php $_categories = $this->getCurrentChildCategories() ?> <?php $_count = […]
  • Get product count of Parent Category (3)
    Trying to get the product count of a category which also counts the products in its children. Currently, I have: $categories = Mage::getModel('catalog/category')->getCollection() ->addAttributeToSelect('*') ->addAttributeToFilter('level', 2) […]
  • getProductCount() function returning similar result for every category (1)
    Hello I am trying to get category name and category product count using category Id . In my results I am getting exact category name but product count is duplicating. foreach ($category as $categoryId) { if (!is_null($categoryId)) { $categoryLoadData = […]
  • getProductCount() function returning similar result for every category (1)
    Hello I am trying to get category name and category product count using category Id . In my results I am getting exact category name but product count is duplicating. foreach ($category as $categoryId) { if (!is_null($categoryId)) { $categoryLoadData = […]
  • Side Category for Magento (2)
    My Magento store uses the following code to view categories navigation on the side column: <?php $_categories = $this->getCurrentChildCategories() ?> <?php $_count = is_array($_categories)?count($_categories):$_categories->count(); ?> <?php function […]
  • Replace Dropdown with Swatches for configrable product on category page (0)
    Using the Below Code i have implemented product view like (where you can select option and add product from list page only) configurable option on category page app/design/frontend/rwd/default/template/catalog/product/view/type/configurable_category.phtml <?php $_product = […]
  • How to wait until text/x-magento-init has loaded the options (2)
    It seems to me that text/x-magento-init returns options async: <script type="text/x-magento-init"> { "*": { "component": " <?php echo "test" ?> " } } </script> component.js define([ 'jquery', 'jquery/ui' ], […]
  • M2.1 – Custom Product List Page To List Best Seller Product (0)
    I need a custom page say /best-seller, where i want to show products with attribute my_attribute_best = yes. Which is similar to /products?my_attribute_best=yes. I did using filter option but layered navigation and paging is not working (Count Is Different)
Custom theme reuse Lumas start page
How to display HTML from uiComponent returning JSON

3 Comments on this article

  • User November 12, 2016

    Three hours later…

    This will render from a category page. You may have to modify to work with your exact requirements.

    Add this block to your Module: Block/CategoryCollect.php

    <?php
    namespace Joshua34UpdateHeadBlock;
    class CategoryCollect extends MagentoFrameworkViewElementTemplate
    {
        protected $_categoryHelper;
        protected $categoryFlatConfig;
        protected $topMenu;
    
        /**
         * @param MagentoFrameworkViewElementTemplateContext $context
         * @param MagentoCatalogHelperCategory $categoryHelper
         * @param array $data
         */
        public function __construct(
            MagentoFrameworkViewElementTemplateContext $context,
            MagentoCatalogHelperCategory $categoryHelper,
            MagentoCatalogModelIndexerCategoryFlatState $categoryFlatState,
            MagentoThemeBlockHtmlTopmenu $topMenu
        )
        {
            $this->_categoryHelper = $categoryHelper;
            $this->categoryFlatConfig = $categoryFlatState;
            $this->topMenu = $topMenu;
            parent::__construct($context);
        }
    
        /**
         * Return categories helper
         */
        public function getCategoryHelper()
        {
            return $this->_categoryHelper;
        }
    
        /**
         * Return categories helper
         * getHtml($outermostClass = '', $childrenWrapClass = '', $limit = 0)
         * example getHtml('level-top', 'submenu', 0)
         */
        public function getHtml()
        {
            return $this->topMenu->getHtml();
        }
    
        /**
         * Retrieve current store categories
         *
         * @param bool|string $sorted
         * @param bool $asCollection
         * @param bool $toLoad
         * @return MagentoFrameworkDataTreeNodeCollection|MagentoCatalogModelResourceCategoryCollection|array
         */
        public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
        {
            return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
        }
    
        /**
         * Retrieve child store categories
         *
         */
        public function getChildCategories($category)
        {
            if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
                $subcategories = (array)$category->getChildrenNodes();
            } else {
                $subcategories = $category->getChildren();
            }
            return $subcategories;
        }
    }
    

    Add this template file to your Module: view/frontend/templates/categorycollect.phtml

    <?php
    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $category = $objectManager->get('MagentoFrameworkRegistry')->registry('current_category');//get current category
    $subcats = $category->getChildrenCategories();
    $_helper = $this->helper('MagentoCatalogHelperOutput');
    ?>
    <ul>
        <?php
        foreach ($subcats as $subcat) {
            if ($subcat->getIsActive()) {
                $_category = $objectManager->create('MagentoCatalogModelCategory')->load($subcat->getId());
                $_outputhelper = $this->helper('MagentoCatalogHelperOutput');
                $subcaturl = $subcat->getUrl();
    
                $_imgHtml = '';
                if ($_imgUrl = $_category->getImageUrl()) {
    
                    $_imgHtml = '<img src="' . $_imgUrl . '" />';
                    $_imgHtml = $_outputhelper->categoryAttribute($_category, $_imgHtml, 'image');
    
                    /* @escapeNotVerified */
                    echo '<li><a href="' . $subcaturl . '" class="block-promo" title="' . $subcat->getName() . '">' . $_imgHtml . '<span style="background-color: rgba(255,255,255,0.9)" class="content bg-white"><strong>Place custom code here</strong><br><br><span class="action more button">Learn More</span></span></a></li>';
                }
            }
        } ?>
    </ul>
    

    Reference from within CMS block / page

     {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}
    

    Reply

  • User November 12, 2016

    To me:

    $block->getCategory($_category)->getImageUrl();
    

    Means that you are retrieving the main category of the block so yeah to fix that, I reckon you should modify your code to this:

    $_category->getImageUrl();
    

    Reply

  • User November 12, 2016

    The simplest solution is to do this:

    $thecat = Mage::getModel('catalog/category')->load($cat->getId());
    

    You can then use

    $thecat->getImageUrl()
    

    to get the category image url.

    Reply

Add a comment