Getting Sub Category Images in Magento2 The Next CEO of Stack OverflowMagento 2 - Show...

Interfacing a button to MCU (and PC) with 50m long cable

Should I tutor a student who I know has cheated on their homework?

Would a completely good Muggle be able to use a wand?

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Preparing Indesign booklet with .psd graphics for print

Why does standard notation not preserve intervals (visually)

Is 'diverse range' a pleonastic phrase?

Grabbing quick drinks

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Complex fractions

Won the lottery - how do I keep the money?

Would a galaxy be visible from outside, but nearby?

Is "for causing autism in X" grammatical?

Does it take more energy to get to Venus or to Mars?

Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log

Written every which way

Is there a difference between "Fahrstuhl" and "Aufzug"

How long to clear the 'suck zone' of a turbofan after start is initiated?

Do I need to enable Dev Hub in my PROD Org?

Solidity! Invalid implicit conversion from string memory to bytes memory requested

Is it professional to write unrelated content in an almost-empty email?

Novel about a guy who is possessed by the divine essence and the world ends?

Why didn't Khan get resurrected in the Genesis Explosion?

Is it possible to search for a directory/file combination?



Getting Sub Category Images in Magento2



The Next CEO of Stack OverflowMagento 2 - Show subcategories (and products) on category pageMagento 2 get image for Subcategory CollectionMagento 2.2. - Show subcategories on category pageCrop Images (category Image) on own templatesShow parent category in a sub-categoryCreate a sub-list of imagesChange Category Images from .png to .jpgResize & Crop Category ImagesGet sub category of current category in magento2GET Magento2 category product imagesCategory and sub category image widgetMagento 2: Sub category showing product from other sub categoryGetting error while adding category Magento2












1















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.










share|improve this question





























    1















    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.










    share|improve this question



























      1












      1








      1


      2






      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.










      share|improve this question
















      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.







      magento2 category image






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 9 at 6:56









      Teja Bhagavan Kollepara

      3,01241949




      3,01241949










      asked Apr 7 '16 at 16:08









      JimmeryJimmery

      70721636




      70721636






















          4 Answers
          4






          active

          oldest

          votes


















          9














          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"}}





          share|improve this answer


























          • Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

            – Raphael at Digital Pianism
            Apr 8 '16 at 8:19






          • 4





            Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

            – Joshua34
            Apr 8 '16 at 13:34











          • @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

            – Jimmery
            Apr 21 '16 at 15:37











          • Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

            – Joshua34
            Apr 21 '16 at 15:56













          • Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

            – Joshua34
            Apr 21 '16 at 15:57





















          2














          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();





          share|improve this answer
























          • I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

            – Jimmery
            Apr 7 '16 at 16:16











          • yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

            – Raphael at Digital Pianism
            Apr 8 '16 at 8:18











          • How can I modify the collection?

            – Jimmery
            Apr 21 '16 at 15:38



















          1














          You can add attributes to child category collections with a plugin, here's an example module (code not tested):



          ./composer.json



          {
          "name": "stackoverflow/module-child-category-image",
          "require": {
          "magento/framework": "101.*",
          "magento/magento-composer-installer": "*"
          },
          "type": "magento2-module",
          "autoload": {
          "files": [
          "registration.php"
          ],
          "psr-4": {
          "StackOverflow\ChildCategoryImage\": ""
          }
          }
          }


          ./registration.php



          <?php
          MagentoFrameworkComponentComponentRegistrar::register(
          MagentoFrameworkComponentComponentRegistrar::MODULE,
          'StackOverflow_ChildCategoryImage',
          __DIR__
          );


          ./etc/module.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
          <module name="StackOverflow_ChildCategoryImage" setup_version="1.0.0">
          <sequence>
          <module name="Magento_Catalog"/>
          </sequence>
          </module>
          </config>


          ./etc/di.xml



          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoCatalogModelResourceModelCategory">
          <plugin name="category" type="StackOverflowChildCategoryImagePluginCategory" />
          </type>
          </config>


          ./etc/frontend/events.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
          <event name="catalog_category_flat_loadnodes_before">
          <observer name="category_flat_add_image" instance="StackOverflowChildCategoryImageObserverFlatCategory" />
          </event>
          </config>


          ./Plugin/Category.php



          <?php
          namespace StackOverflowChildCategoryImagePlugin;

          use MagentoCatalogModelResourceModelCategory as Subject;

          class Category
          {
          /**
          * Add Image to Child Category Collection
          *
          * @param Subject $subject
          * @param MagentoCatalogModelCategory $category
          * @return MagentoCatalogModelResourceModelCategoryCollection
          */
          public function afterGetChildrenCategories(
          Subject $subject,
          $collection
          ) {
          $collection->addAttributeToSelect('image_url');
          return $collection;
          }
          }


          ./Observer/FlatCategory.php



          <?php
          namespace StackOverflowChildCategoryImageObserver;

          use MagentoFrameworkEventObserverInterface;
          use MagentoFrameworkEventObserver;

          class FlatCategory implements ObserverInterface
          {
          public function execute(
          Observer $observer
          ) {
          $select = $observer->getData('select');
          $select->columns('image_url');
          }
          }





          share|improve this answer































            0














            Lots of solutions above would cause serious performance issues. Try this.



            $_category  = $block->getCurrentCategory();
            $_subCategories = $_category->getChildrenCategories()->addAttributeToSelect('image');
            <?php foreach ($_subCategories as $_sub):?>
            <?php echo($_sub->getImageUrl());?>
            <?php endforeach;?>




            share








            New contributor




            Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





















              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "479"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f110003%2fgetting-sub-category-images-in-magento2%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              9














              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"}}





              share|improve this answer


























              • Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:19






              • 4





                Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

                – Joshua34
                Apr 8 '16 at 13:34











              • @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

                – Jimmery
                Apr 21 '16 at 15:37











              • Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

                – Joshua34
                Apr 21 '16 at 15:56













              • Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

                – Joshua34
                Apr 21 '16 at 15:57


















              9














              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"}}





              share|improve this answer


























              • Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:19






              • 4





                Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

                – Joshua34
                Apr 8 '16 at 13:34











              • @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

                – Jimmery
                Apr 21 '16 at 15:37











              • Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

                – Joshua34
                Apr 21 '16 at 15:56













              • Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

                – Joshua34
                Apr 21 '16 at 15:57
















              9












              9








              9







              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"}}





              share|improve this answer















              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"}}






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 21 '16 at 16:12









              Siarhey Uchukhlebau

              9,92693058




              9,92693058










              answered Apr 7 '16 at 18:20









              Joshua34Joshua34

              1,5691120




              1,5691120













              • Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:19






              • 4





                Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

                – Joshua34
                Apr 8 '16 at 13:34











              • @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

                – Jimmery
                Apr 21 '16 at 15:37











              • Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

                – Joshua34
                Apr 21 '16 at 15:56













              • Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

                – Joshua34
                Apr 21 '16 at 15:57





















              • Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:19






              • 4





                Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

                – Joshua34
                Apr 8 '16 at 13:34











              • @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

                – Jimmery
                Apr 21 '16 at 15:37











              • Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

                – Joshua34
                Apr 21 '16 at 15:56













              • Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

                – Joshua34
                Apr 21 '16 at 15:57



















              Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

              – Raphael at Digital Pianism
              Apr 8 '16 at 8:19





              Even though I assume that would work, loading the entire category is not very efficient in terms of performance and the use of collection with addAttributeToSelect('image') should be preferred

              – Raphael at Digital Pianism
              Apr 8 '16 at 8:19




              4




              4





              Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

              – Joshua34
              Apr 8 '16 at 13:34





              Between me and M2, efficiency is constantly being sacrificed just to accomplish basic tasks. Not enough time, docs or support to discover the "best way" while still accomplishing "a way", in a timely manner.

              – Joshua34
              Apr 8 '16 at 13:34













              @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

              – Jimmery
              Apr 21 '16 at 15:37





              @Joshua34com thanks for this! just want to check - is view/frontend/templatescategorycollect.phtml correct? I have no files there - most of my phtml files are in Magento_Theme/templates - if that place is correct, how do I reference it so it appears on a page of my choice?

              – Jimmery
              Apr 21 '16 at 15:37













              Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

              – Joshua34
              Apr 21 '16 at 15:56







              Sorry, corrected answer spelling. File should be created within your module here: app/code/Vendor/ModuleName/view/frontend/templates/categorycollect.phtml

              – Joshua34
              Apr 21 '16 at 15:56















              Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

              – Joshua34
              Apr 21 '16 at 15:57







              Reference from within CMS block / page like so: {{block class="VendorModuleNameBlockCategoryCollect" template="Vendor_ModuleName::categorycollect.phtml"}}

              – Joshua34
              Apr 21 '16 at 15:57















              2














              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();





              share|improve this answer
























              • I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

                – Jimmery
                Apr 7 '16 at 16:16











              • yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:18











              • How can I modify the collection?

                – Jimmery
                Apr 21 '16 at 15:38
















              2














              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();





              share|improve this answer
























              • I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

                – Jimmery
                Apr 7 '16 at 16:16











              • yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:18











              • How can I modify the collection?

                – Jimmery
                Apr 21 '16 at 15:38














              2












              2








              2







              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();





              share|improve this answer













              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();






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 7 '16 at 16:12









              Raphael at Digital PianismRaphael at Digital Pianism

              55k22121279




              55k22121279













              • I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

                – Jimmery
                Apr 7 '16 at 16:16











              • yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:18











              • How can I modify the collection?

                – Jimmery
                Apr 21 '16 at 15:38



















              • I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

                – Jimmery
                Apr 7 '16 at 16:16











              • yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

                – Raphael at Digital Pianism
                Apr 8 '16 at 8:18











              • How can I modify the collection?

                – Jimmery
                Apr 21 '16 at 15:38

















              I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

              – Jimmery
              Apr 7 '16 at 16:16





              I agree with your first point, however $_category->getImageUrl(); only returns false. When I do a var_dump(get_class_methods($_category)); there doesnt seem to be anything there that relates to images.

              – Jimmery
              Apr 7 '16 at 16:16













              yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

              – Raphael at Digital Pianism
              Apr 8 '16 at 8:18





              yeah problem is the image is not part of the child categories attribute that's why you get nothing I reckon you'll have to modify the collection to select the image

              – Raphael at Digital Pianism
              Apr 8 '16 at 8:18













              How can I modify the collection?

              – Jimmery
              Apr 21 '16 at 15:38





              How can I modify the collection?

              – Jimmery
              Apr 21 '16 at 15:38











              1














              You can add attributes to child category collections with a plugin, here's an example module (code not tested):



              ./composer.json



              {
              "name": "stackoverflow/module-child-category-image",
              "require": {
              "magento/framework": "101.*",
              "magento/magento-composer-installer": "*"
              },
              "type": "magento2-module",
              "autoload": {
              "files": [
              "registration.php"
              ],
              "psr-4": {
              "StackOverflow\ChildCategoryImage\": ""
              }
              }
              }


              ./registration.php



              <?php
              MagentoFrameworkComponentComponentRegistrar::register(
              MagentoFrameworkComponentComponentRegistrar::MODULE,
              'StackOverflow_ChildCategoryImage',
              __DIR__
              );


              ./etc/module.xml



              <?xml version="1.0"?>
              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
              <module name="StackOverflow_ChildCategoryImage" setup_version="1.0.0">
              <sequence>
              <module name="Magento_Catalog"/>
              </sequence>
              </module>
              </config>


              ./etc/di.xml



              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
              <type name="MagentoCatalogModelResourceModelCategory">
              <plugin name="category" type="StackOverflowChildCategoryImagePluginCategory" />
              </type>
              </config>


              ./etc/frontend/events.xml



              <?xml version="1.0"?>
              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
              <event name="catalog_category_flat_loadnodes_before">
              <observer name="category_flat_add_image" instance="StackOverflowChildCategoryImageObserverFlatCategory" />
              </event>
              </config>


              ./Plugin/Category.php



              <?php
              namespace StackOverflowChildCategoryImagePlugin;

              use MagentoCatalogModelResourceModelCategory as Subject;

              class Category
              {
              /**
              * Add Image to Child Category Collection
              *
              * @param Subject $subject
              * @param MagentoCatalogModelCategory $category
              * @return MagentoCatalogModelResourceModelCategoryCollection
              */
              public function afterGetChildrenCategories(
              Subject $subject,
              $collection
              ) {
              $collection->addAttributeToSelect('image_url');
              return $collection;
              }
              }


              ./Observer/FlatCategory.php



              <?php
              namespace StackOverflowChildCategoryImageObserver;

              use MagentoFrameworkEventObserverInterface;
              use MagentoFrameworkEventObserver;

              class FlatCategory implements ObserverInterface
              {
              public function execute(
              Observer $observer
              ) {
              $select = $observer->getData('select');
              $select->columns('image_url');
              }
              }





              share|improve this answer




























                1














                You can add attributes to child category collections with a plugin, here's an example module (code not tested):



                ./composer.json



                {
                "name": "stackoverflow/module-child-category-image",
                "require": {
                "magento/framework": "101.*",
                "magento/magento-composer-installer": "*"
                },
                "type": "magento2-module",
                "autoload": {
                "files": [
                "registration.php"
                ],
                "psr-4": {
                "StackOverflow\ChildCategoryImage\": ""
                }
                }
                }


                ./registration.php



                <?php
                MagentoFrameworkComponentComponentRegistrar::register(
                MagentoFrameworkComponentComponentRegistrar::MODULE,
                'StackOverflow_ChildCategoryImage',
                __DIR__
                );


                ./etc/module.xml



                <?xml version="1.0"?>
                <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
                <module name="StackOverflow_ChildCategoryImage" setup_version="1.0.0">
                <sequence>
                <module name="Magento_Catalog"/>
                </sequence>
                </module>
                </config>


                ./etc/di.xml



                <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
                <type name="MagentoCatalogModelResourceModelCategory">
                <plugin name="category" type="StackOverflowChildCategoryImagePluginCategory" />
                </type>
                </config>


                ./etc/frontend/events.xml



                <?xml version="1.0"?>
                <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
                <event name="catalog_category_flat_loadnodes_before">
                <observer name="category_flat_add_image" instance="StackOverflowChildCategoryImageObserverFlatCategory" />
                </event>
                </config>


                ./Plugin/Category.php



                <?php
                namespace StackOverflowChildCategoryImagePlugin;

                use MagentoCatalogModelResourceModelCategory as Subject;

                class Category
                {
                /**
                * Add Image to Child Category Collection
                *
                * @param Subject $subject
                * @param MagentoCatalogModelCategory $category
                * @return MagentoCatalogModelResourceModelCategoryCollection
                */
                public function afterGetChildrenCategories(
                Subject $subject,
                $collection
                ) {
                $collection->addAttributeToSelect('image_url');
                return $collection;
                }
                }


                ./Observer/FlatCategory.php



                <?php
                namespace StackOverflowChildCategoryImageObserver;

                use MagentoFrameworkEventObserverInterface;
                use MagentoFrameworkEventObserver;

                class FlatCategory implements ObserverInterface
                {
                public function execute(
                Observer $observer
                ) {
                $select = $observer->getData('select');
                $select->columns('image_url');
                }
                }





                share|improve this answer


























                  1












                  1








                  1







                  You can add attributes to child category collections with a plugin, here's an example module (code not tested):



                  ./composer.json



                  {
                  "name": "stackoverflow/module-child-category-image",
                  "require": {
                  "magento/framework": "101.*",
                  "magento/magento-composer-installer": "*"
                  },
                  "type": "magento2-module",
                  "autoload": {
                  "files": [
                  "registration.php"
                  ],
                  "psr-4": {
                  "StackOverflow\ChildCategoryImage\": ""
                  }
                  }
                  }


                  ./registration.php



                  <?php
                  MagentoFrameworkComponentComponentRegistrar::register(
                  MagentoFrameworkComponentComponentRegistrar::MODULE,
                  'StackOverflow_ChildCategoryImage',
                  __DIR__
                  );


                  ./etc/module.xml



                  <?xml version="1.0"?>
                  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
                  <module name="StackOverflow_ChildCategoryImage" setup_version="1.0.0">
                  <sequence>
                  <module name="Magento_Catalog"/>
                  </sequence>
                  </module>
                  </config>


                  ./etc/di.xml



                  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
                  <type name="MagentoCatalogModelResourceModelCategory">
                  <plugin name="category" type="StackOverflowChildCategoryImagePluginCategory" />
                  </type>
                  </config>


                  ./etc/frontend/events.xml



                  <?xml version="1.0"?>
                  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
                  <event name="catalog_category_flat_loadnodes_before">
                  <observer name="category_flat_add_image" instance="StackOverflowChildCategoryImageObserverFlatCategory" />
                  </event>
                  </config>


                  ./Plugin/Category.php



                  <?php
                  namespace StackOverflowChildCategoryImagePlugin;

                  use MagentoCatalogModelResourceModelCategory as Subject;

                  class Category
                  {
                  /**
                  * Add Image to Child Category Collection
                  *
                  * @param Subject $subject
                  * @param MagentoCatalogModelCategory $category
                  * @return MagentoCatalogModelResourceModelCategoryCollection
                  */
                  public function afterGetChildrenCategories(
                  Subject $subject,
                  $collection
                  ) {
                  $collection->addAttributeToSelect('image_url');
                  return $collection;
                  }
                  }


                  ./Observer/FlatCategory.php



                  <?php
                  namespace StackOverflowChildCategoryImageObserver;

                  use MagentoFrameworkEventObserverInterface;
                  use MagentoFrameworkEventObserver;

                  class FlatCategory implements ObserverInterface
                  {
                  public function execute(
                  Observer $observer
                  ) {
                  $select = $observer->getData('select');
                  $select->columns('image_url');
                  }
                  }





                  share|improve this answer













                  You can add attributes to child category collections with a plugin, here's an example module (code not tested):



                  ./composer.json



                  {
                  "name": "stackoverflow/module-child-category-image",
                  "require": {
                  "magento/framework": "101.*",
                  "magento/magento-composer-installer": "*"
                  },
                  "type": "magento2-module",
                  "autoload": {
                  "files": [
                  "registration.php"
                  ],
                  "psr-4": {
                  "StackOverflow\ChildCategoryImage\": ""
                  }
                  }
                  }


                  ./registration.php



                  <?php
                  MagentoFrameworkComponentComponentRegistrar::register(
                  MagentoFrameworkComponentComponentRegistrar::MODULE,
                  'StackOverflow_ChildCategoryImage',
                  __DIR__
                  );


                  ./etc/module.xml



                  <?xml version="1.0"?>
                  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
                  <module name="StackOverflow_ChildCategoryImage" setup_version="1.0.0">
                  <sequence>
                  <module name="Magento_Catalog"/>
                  </sequence>
                  </module>
                  </config>


                  ./etc/di.xml



                  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
                  <type name="MagentoCatalogModelResourceModelCategory">
                  <plugin name="category" type="StackOverflowChildCategoryImagePluginCategory" />
                  </type>
                  </config>


                  ./etc/frontend/events.xml



                  <?xml version="1.0"?>
                  <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
                  <event name="catalog_category_flat_loadnodes_before">
                  <observer name="category_flat_add_image" instance="StackOverflowChildCategoryImageObserverFlatCategory" />
                  </event>
                  </config>


                  ./Plugin/Category.php



                  <?php
                  namespace StackOverflowChildCategoryImagePlugin;

                  use MagentoCatalogModelResourceModelCategory as Subject;

                  class Category
                  {
                  /**
                  * Add Image to Child Category Collection
                  *
                  * @param Subject $subject
                  * @param MagentoCatalogModelCategory $category
                  * @return MagentoCatalogModelResourceModelCategoryCollection
                  */
                  public function afterGetChildrenCategories(
                  Subject $subject,
                  $collection
                  ) {
                  $collection->addAttributeToSelect('image_url');
                  return $collection;
                  }
                  }


                  ./Observer/FlatCategory.php



                  <?php
                  namespace StackOverflowChildCategoryImageObserver;

                  use MagentoFrameworkEventObserverInterface;
                  use MagentoFrameworkEventObserver;

                  class FlatCategory implements ObserverInterface
                  {
                  public function execute(
                  Observer $observer
                  ) {
                  $select = $observer->getData('select');
                  $select->columns('image_url');
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 29 at 14:45









                  ChedarooChedaroo

                  15914




                  15914























                      0














                      Lots of solutions above would cause serious performance issues. Try this.



                      $_category  = $block->getCurrentCategory();
                      $_subCategories = $_category->getChildrenCategories()->addAttributeToSelect('image');
                      <?php foreach ($_subCategories as $_sub):?>
                      <?php echo($_sub->getImageUrl());?>
                      <?php endforeach;?>




                      share








                      New contributor




                      Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.

























                        0














                        Lots of solutions above would cause serious performance issues. Try this.



                        $_category  = $block->getCurrentCategory();
                        $_subCategories = $_category->getChildrenCategories()->addAttributeToSelect('image');
                        <?php foreach ($_subCategories as $_sub):?>
                        <?php echo($_sub->getImageUrl());?>
                        <?php endforeach;?>




                        share








                        New contributor




                        Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.























                          0












                          0








                          0







                          Lots of solutions above would cause serious performance issues. Try this.



                          $_category  = $block->getCurrentCategory();
                          $_subCategories = $_category->getChildrenCategories()->addAttributeToSelect('image');
                          <?php foreach ($_subCategories as $_sub):?>
                          <?php echo($_sub->getImageUrl());?>
                          <?php endforeach;?>




                          share








                          New contributor




                          Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.










                          Lots of solutions above would cause serious performance issues. Try this.



                          $_category  = $block->getCurrentCategory();
                          $_subCategories = $_category->getChildrenCategories()->addAttributeToSelect('image');
                          <?php foreach ($_subCategories as $_sub):?>
                          <?php echo($_sub->getImageUrl());?>
                          <?php endforeach;?>





                          share








                          New contributor




                          Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.








                          share


                          share






                          New contributor




                          Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          answered 9 mins ago









                          Adel Abula - MageBinaryAdel Abula - MageBinary

                          1011




                          1011




                          New contributor




                          Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.





                          New contributor





                          Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          Adel Abula - MageBinary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Magento Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f110003%2fgetting-sub-category-images-in-magento2%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              “%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

                              How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

                              變成蝙蝠會怎樣? 參考資料 外部連結 导航菜单Thomas Nagel, "What is it like to be a...