Magento 2: How to Get Subcategory Image in Category Page?How to get the custom attribute values in my catalog...

Can the electrostatic force be infinite in magnitude?

What do you call the infoboxes with text and sometimes images on the side of a page we find in textbooks?

Identify a stage play about a VR experience in which participants are encouraged to simulate performing horrific activities

Simple recursive Sudoku solver

Lifted its hind leg on or lifted its hind leg towards?

Could solar power be utilized and substitute coal in the 19th century?

Meta programming: Declare a new struct on the fly

What is the oldest known work of fiction?

Why is delta-v is the most useful quantity for planning space travel?

Female=gender counterpart?

Reply ‘no position’ while the job posting is still there (‘HiWi’ position in Germany)

Partial sums of primes

Indicating multiple different modes of speech (fantasy language or telepathy)

Organic chemistry Iodoform Reaction

Superhero words!

How to prevent YouTube from showing already watched videos?

Taylor series of product of two functions

Is there an Impartial Brexit Deal comparison site?

Was the picture area of a CRT a parallelogram (instead of a true rectangle)?

What will be the temperature on Earth when Sun finishes its main sequence?

How to color a zone in Tikz

A workplace installs custom certificates on personal devices, can this be used to decrypt HTTPS traffic?

Installing PowerShell on 32-bit Kali OS fails

Java - What do constructor type arguments mean when placed *before* the type?



Magento 2: How to Get Subcategory Image in Category Page?


How to get the custom attribute values in my catalog category list blockAdding an image only if tier price is shownGet closest parent category imagehow to get corresponding associated products images in magentoExcluding one or more subcategory in a Category Page that displays Subcategory listGet Full Image path on frontend uploaded from custom field in databaseCustom Attribute Value not getting in Category Page in Magento 2Custom Category Page Layout Static Block to bottomCreate Product Finder PageGet sub-categories listing of parent in Magento 2 CMS block













0















I want to display subcategory in category page with the image.
I've to put below code get only subcategory name not getting the image.



How to get subcategory image in category page?



if($this->getLayer()->getCurrentCategory())

$subcategories=$this->getLayer()->getCurrentCategory()->getCategories($this->getLayer()->getCurrentCategory()->getId());


if($subcategories->count()>0){

foreach($subcategories as $subcategory){

<li>
<a href="<?php echo $subcategory->getRequest_path(); ?>"><?php echo $subcategory->getName() ?></a>
</li>
}
}else{}

endif;









share|improve this question

























  • use this $subcategory->getImageUrl();

    – MagikVishal
    Jun 15 '16 at 9:19











  • Also Use $subcategory->getImageUrl(); code to GetImageUrl but not getting Image url.

    – Nikul
    Jun 15 '16 at 10:00


















0















I want to display subcategory in category page with the image.
I've to put below code get only subcategory name not getting the image.



How to get subcategory image in category page?



if($this->getLayer()->getCurrentCategory())

$subcategories=$this->getLayer()->getCurrentCategory()->getCategories($this->getLayer()->getCurrentCategory()->getId());


if($subcategories->count()>0){

foreach($subcategories as $subcategory){

<li>
<a href="<?php echo $subcategory->getRequest_path(); ?>"><?php echo $subcategory->getName() ?></a>
</li>
}
}else{}

endif;









share|improve this question

























  • use this $subcategory->getImageUrl();

    – MagikVishal
    Jun 15 '16 at 9:19











  • Also Use $subcategory->getImageUrl(); code to GetImageUrl but not getting Image url.

    – Nikul
    Jun 15 '16 at 10:00
















0












0








0


1






I want to display subcategory in category page with the image.
I've to put below code get only subcategory name not getting the image.



How to get subcategory image in category page?



if($this->getLayer()->getCurrentCategory())

$subcategories=$this->getLayer()->getCurrentCategory()->getCategories($this->getLayer()->getCurrentCategory()->getId());


if($subcategories->count()>0){

foreach($subcategories as $subcategory){

<li>
<a href="<?php echo $subcategory->getRequest_path(); ?>"><?php echo $subcategory->getName() ?></a>
</li>
}
}else{}

endif;









share|improve this question
















I want to display subcategory in category page with the image.
I've to put below code get only subcategory name not getting the image.



How to get subcategory image in category page?



if($this->getLayer()->getCurrentCategory())

$subcategories=$this->getLayer()->getCurrentCategory()->getCategories($this->getLayer()->getCurrentCategory()->getId());


if($subcategories->count()>0){

foreach($subcategories as $subcategory){

<li>
<a href="<?php echo $subcategory->getRequest_path(); ?>"><?php echo $subcategory->getName() ?></a>
</li>
}
}else{}

endif;






catalog image magento-2.0 category-view






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 8 '17 at 4:28









Rafael Corrêa Gomes

4,60223265




4,60223265










asked Jun 15 '16 at 8:56









NikulNikul

691918




691918













  • use this $subcategory->getImageUrl();

    – MagikVishal
    Jun 15 '16 at 9:19











  • Also Use $subcategory->getImageUrl(); code to GetImageUrl but not getting Image url.

    – Nikul
    Jun 15 '16 at 10:00





















  • use this $subcategory->getImageUrl();

    – MagikVishal
    Jun 15 '16 at 9:19











  • Also Use $subcategory->getImageUrl(); code to GetImageUrl but not getting Image url.

    – Nikul
    Jun 15 '16 at 10:00



















use this $subcategory->getImageUrl();

– MagikVishal
Jun 15 '16 at 9:19





use this $subcategory->getImageUrl();

– MagikVishal
Jun 15 '16 at 9:19













Also Use $subcategory->getImageUrl(); code to GetImageUrl but not getting Image url.

– Nikul
Jun 15 '16 at 10:00







Also Use $subcategory->getImageUrl(); code to GetImageUrl but not getting Image url.

– Nikul
Jun 15 '16 at 10:00












4 Answers
4






active

oldest

votes


















1














i used this block to have the same functionality and called the block in xml ( don't forget to create a template for the block with the desired functionality and html mockup



namespace NamespaceModule_NameBlock;

class Subcategories extends MagentoFrameworkViewElementTemplate
{

/**
* @var MagentoFrameworkRegistry
*/
protected $_registry;

/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
protected $_categoryCollectionFactory;

/**
* @var MagentoCatalogHelperCategory
*/
protected $_categoryHelper;

/**
* Subcategories constructor.
* @param MagentoBackendBlockTemplateContext $context
* @param MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
* @param MagentoCatalogHelperCategory $categoryHelper
* @param MagentoFrameworkRegistry $registry
* @param array $data
*/
public function __construct(
MagentoBackendBlockTemplateContext $context,
MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory,
MagentoCatalogHelperCategory $categoryHelper,
MagentoFrameworkRegistry $registry,
array $data = []
)
{
$this->_registry = $registry;
$this->_categoryCollectionFactory = $categoryCollectionFactory;
$this->_categoryHelper = $categoryHelper;
parent::__construct($context, $data);
}


public function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}


public function getCategoryCollection(){
$_category = $this->getCurrentCategory();
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addAttributeToFilter('is_active', 1)
->setOrder('position', 'ASC')
->addIdFilter($_category->getChildren());

return $collection;
}


}





share|improve this answer

































    0














    I did this by creating a preference for MagentoModelResourceModelCategory and an observer for MagentoModelResourceModelCategoryFlat.



    Create a Module




    app/code/{vendor_name}/{module_name}




    Create




    app/code/{vendor_name}/{module_name}/registration.php




    MagentoFrameworkComponentComponentRegistrar::register(
    MagentoFrameworkComponentComponentRegistrar::MODULE,
    '{vendor_name}_{module_name}',
    __DIR__
    );



    app/code/{vendor_name}/{module_name}/etc/module.xml




    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="{vendor_name}_{module_name}" setup_version="1.0.0"></module>
    </config>



    app/code/{vendor_name}/{module_name}/etc/di.xml




    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="MagentoCatalogModelResourceModelCategory" type="{vendor_name}{module_name}{path_to_class i.e ModelResourceModelCategory}" />
    </config>


    I've just used the same name as the file this is taking precedence over but this is optional.




    app/code/{vendor_name}/{module_name}ModelResourceModelCategory.php




    namespace {vendor_name}{module_name}ModelResourceModel;

    class Category extends MagentoCatalogModelResourceModelCategory
    {
    /* Override this method */

    public function getChildrenCategories($category)
    {
    $collection = $category->getCollection();
    /* @var $collection
    MagentoCatalogModelResourceModelCategoryCollection */
    $collection->addAttributeToSelect(
    'url_key'
    )->addAttributeToSelect(
    'name'
    )->

    /* Add this section to select image */
    addAttributeToSelect(
    'image'
    )->
    /* Add this section to select image */

    addAttributeToSelect(
    'all_children'
    )->addAttributeToSelect(
    'is_anchor'
    )->addAttributeToFilter(
    'is_active',
    1
    )->addIdFilter(
    $category->getChildren()
    )->setOrder(
    'position',
    MagentoFrameworkDBSelect::SQL_ASC
    )->joinUrlRewrite()->load();

    return $collection;
    }
    }


    Ideally I would have used a plugin here, but sadly because of how this method is defined I don't see how I can.



    I used Magento_Catalog/template/category/description.phtml to output my subcategories, I'm using the category main image as a thumbnail.



    <?php if ($_description = $_category->getDescription()): ?>
    <div class="category-description">
    <?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_category, $_description, 'description') ?>
    </div>
    <?php endif; ?>

    <?php if($_category->hasChildren()): ?>
    <div class="categories wrapper grid categories-grid">
    <ul class="categories list items categories-items">
    <?php foreach($_category->getChildrenCategories() as $_child): ?>
    <?php if($_child->getIsActive()): ?>
    <li class="item category category-item">
    <?php if($_child->getImageUrl()): ?> <!-- We can now use getImageUrl() on child categories -->
    <a href="<?php echo $_child->getUrl() ?>" class="category photo category-item-photo" tabindex="-1">
    <span class="category-image-container">
    <span class="category-image-wrapper" style="padding-bottom: 125%;">
    <img class="category-image-photo" src="<?php echo $_child->getImageUrl(); ?>" alt="<?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?>" />
    </span>
    </span>
    </a>
    <?php endif; ?>
    <strong class="category name category-item-name">
    <a class="category-item-link" href="<?php echo $_child->getUrl() ?>"><?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?></a>
    </strong>
    </li>
    <?php endif; ?>
    <?php endforeach; ?>
    </ul>
    </div>
    <?php endif; ?>


    This works great for EAV mode but doesn't work in flat category mode, to fix that we need to create an observer, oddly Magento provides a hook/event to modify the database query in flat category mode, but not in EAV mode.



    Create




    app/code/{vendor_name}/{module_name}/etc/frontend/events.xml




    I've used frontend here as I'm only interested in observing this event on the frontend.



    <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="{uour_unique_observer_name}" instance="{vendor_name}/{module_name}/Observer/{Whatever i.e CategoryFlatObserver}" />
    </event>




    Finally an observer class




    app/code/{vendor_name}/{module_name}/Observer/{your_observer_name




    i.e FlatCategoryObserver.php}`



    namespace {vendor_name}{module_name}Observer;

    use MagentoFrameworkEventObserverInterface;

    class CategoryFlatObserver implements ObserverInterface
    {
    public function execute(MagentoFrameworkEventObserver $observer)
    {
    $select = $observer->getData('select');
    $select->columns('image');
    }
    }


    Now anywhere the category resource model and getChildrenCategories() method is used on the frontend it will select the category image. Need to do a setup:upgrade and clear all caches before this will work.






    share|improve this answer


























    • Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

      – Octoxan
      Feb 28 '18 at 15:44











    • @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

      – 4D1
      Apr 6 '18 at 14:35





















    0














    If you are still looking for a solution to show Subcategories on parent category page. Have a look at Advanced Subcategory Grid module on Magento2 Marketplace that can be used to show subcategories on category pages, its highly customizable and also supports configurable color swatches as-well.






    share|improve this answer































      -1














      I have Put Below Code Magento_Catalog/templates/category/products.phtml File and Get all Subcategory Images and Data.



      $_helper    = $this->helper('MagentoCatalogHelperOutput');
      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
      $category = $objectManager->get('MagentoFrameworkRegistry')->registry('current_category');
      $childcategories = $category->getChildrenCategories();
      $sub_category_count = count($childcategories);

      if($sub_category_count != 0){
      echo '<ul>';
      foreach($childcategories as $child)
      {
      echo '<li class="sub-cat">';
      $cat = $objectManager->create('MagentoCatalogModelCategory')->load($child->getId());

      if ($_imgUrl = $cat->getImageUrl())
      {
      $_imgHtml = '<div class="category-image"><img src="' . $_imgUrl . '" alt="' . $block->escapeHtml($cat->getName()) . '" title="' . $block->escapeHtml($cat->getName()) . '" class="image" /></div>';
      $_imgHtml = $_helper->categoryAttribute($cat, $_imgHtml, 'image');
      /* @escapeNotVerified */ echo $_imgHtml;
      }

      echo '</li>'; }
      echo '</ul>';
      } else {
      if (!$block->isContentMode() || $block->isMixedMode()):
      echo $block->getProductListHtml();
      endif;
      }


      It's Working Fine for me.






      share|improve this answer
























      • You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

        – Vlad Patru
        Apr 6 '17 at 20:57











      • Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

        – Toan Nguyen
        Aug 14 '17 at 4:58











      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%2f120977%2fmagento-2-how-to-get-subcategory-image-in-category-page%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









      1














      i used this block to have the same functionality and called the block in xml ( don't forget to create a template for the block with the desired functionality and html mockup



      namespace NamespaceModule_NameBlock;

      class Subcategories extends MagentoFrameworkViewElementTemplate
      {

      /**
      * @var MagentoFrameworkRegistry
      */
      protected $_registry;

      /**
      * @var MagentoCatalogModelResourceModelCategoryCollectionFactory
      */
      protected $_categoryCollectionFactory;

      /**
      * @var MagentoCatalogHelperCategory
      */
      protected $_categoryHelper;

      /**
      * Subcategories constructor.
      * @param MagentoBackendBlockTemplateContext $context
      * @param MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
      * @param MagentoCatalogHelperCategory $categoryHelper
      * @param MagentoFrameworkRegistry $registry
      * @param array $data
      */
      public function __construct(
      MagentoBackendBlockTemplateContext $context,
      MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory,
      MagentoCatalogHelperCategory $categoryHelper,
      MagentoFrameworkRegistry $registry,
      array $data = []
      )
      {
      $this->_registry = $registry;
      $this->_categoryCollectionFactory = $categoryCollectionFactory;
      $this->_categoryHelper = $categoryHelper;
      parent::__construct($context, $data);
      }


      public function getCurrentCategory()
      {
      return $this->_registry->registry('current_category');
      }


      public function getCategoryCollection(){
      $_category = $this->getCurrentCategory();
      $collection = $this->_categoryCollectionFactory->create();
      $collection->addAttributeToSelect('*')
      ->addAttributeToFilter('is_active', 1)
      ->setOrder('position', 'ASC')
      ->addIdFilter($_category->getChildren());

      return $collection;
      }


      }





      share|improve this answer






























        1














        i used this block to have the same functionality and called the block in xml ( don't forget to create a template for the block with the desired functionality and html mockup



        namespace NamespaceModule_NameBlock;

        class Subcategories extends MagentoFrameworkViewElementTemplate
        {

        /**
        * @var MagentoFrameworkRegistry
        */
        protected $_registry;

        /**
        * @var MagentoCatalogModelResourceModelCategoryCollectionFactory
        */
        protected $_categoryCollectionFactory;

        /**
        * @var MagentoCatalogHelperCategory
        */
        protected $_categoryHelper;

        /**
        * Subcategories constructor.
        * @param MagentoBackendBlockTemplateContext $context
        * @param MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
        * @param MagentoCatalogHelperCategory $categoryHelper
        * @param MagentoFrameworkRegistry $registry
        * @param array $data
        */
        public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory,
        MagentoCatalogHelperCategory $categoryHelper,
        MagentoFrameworkRegistry $registry,
        array $data = []
        )
        {
        $this->_registry = $registry;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryHelper = $categoryHelper;
        parent::__construct($context, $data);
        }


        public function getCurrentCategory()
        {
        return $this->_registry->registry('current_category');
        }


        public function getCategoryCollection(){
        $_category = $this->getCurrentCategory();
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*')
        ->addAttributeToFilter('is_active', 1)
        ->setOrder('position', 'ASC')
        ->addIdFilter($_category->getChildren());

        return $collection;
        }


        }





        share|improve this answer




























          1












          1








          1







          i used this block to have the same functionality and called the block in xml ( don't forget to create a template for the block with the desired functionality and html mockup



          namespace NamespaceModule_NameBlock;

          class Subcategories extends MagentoFrameworkViewElementTemplate
          {

          /**
          * @var MagentoFrameworkRegistry
          */
          protected $_registry;

          /**
          * @var MagentoCatalogModelResourceModelCategoryCollectionFactory
          */
          protected $_categoryCollectionFactory;

          /**
          * @var MagentoCatalogHelperCategory
          */
          protected $_categoryHelper;

          /**
          * Subcategories constructor.
          * @param MagentoBackendBlockTemplateContext $context
          * @param MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
          * @param MagentoCatalogHelperCategory $categoryHelper
          * @param MagentoFrameworkRegistry $registry
          * @param array $data
          */
          public function __construct(
          MagentoBackendBlockTemplateContext $context,
          MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory,
          MagentoCatalogHelperCategory $categoryHelper,
          MagentoFrameworkRegistry $registry,
          array $data = []
          )
          {
          $this->_registry = $registry;
          $this->_categoryCollectionFactory = $categoryCollectionFactory;
          $this->_categoryHelper = $categoryHelper;
          parent::__construct($context, $data);
          }


          public function getCurrentCategory()
          {
          return $this->_registry->registry('current_category');
          }


          public function getCategoryCollection(){
          $_category = $this->getCurrentCategory();
          $collection = $this->_categoryCollectionFactory->create();
          $collection->addAttributeToSelect('*')
          ->addAttributeToFilter('is_active', 1)
          ->setOrder('position', 'ASC')
          ->addIdFilter($_category->getChildren());

          return $collection;
          }


          }





          share|improve this answer















          i used this block to have the same functionality and called the block in xml ( don't forget to create a template for the block with the desired functionality and html mockup



          namespace NamespaceModule_NameBlock;

          class Subcategories extends MagentoFrameworkViewElementTemplate
          {

          /**
          * @var MagentoFrameworkRegistry
          */
          protected $_registry;

          /**
          * @var MagentoCatalogModelResourceModelCategoryCollectionFactory
          */
          protected $_categoryCollectionFactory;

          /**
          * @var MagentoCatalogHelperCategory
          */
          protected $_categoryHelper;

          /**
          * Subcategories constructor.
          * @param MagentoBackendBlockTemplateContext $context
          * @param MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
          * @param MagentoCatalogHelperCategory $categoryHelper
          * @param MagentoFrameworkRegistry $registry
          * @param array $data
          */
          public function __construct(
          MagentoBackendBlockTemplateContext $context,
          MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory,
          MagentoCatalogHelperCategory $categoryHelper,
          MagentoFrameworkRegistry $registry,
          array $data = []
          )
          {
          $this->_registry = $registry;
          $this->_categoryCollectionFactory = $categoryCollectionFactory;
          $this->_categoryHelper = $categoryHelper;
          parent::__construct($context, $data);
          }


          public function getCurrentCategory()
          {
          return $this->_registry->registry('current_category');
          }


          public function getCategoryCollection(){
          $_category = $this->getCurrentCategory();
          $collection = $this->_categoryCollectionFactory->create();
          $collection->addAttributeToSelect('*')
          ->addAttributeToFilter('is_active', 1)
          ->setOrder('position', 'ASC')
          ->addIdFilter($_category->getChildren());

          return $collection;
          }


          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 6 '17 at 21:31

























          answered Apr 6 '17 at 21:01









          Vlad PatruVlad Patru

          848416




          848416

























              0














              I did this by creating a preference for MagentoModelResourceModelCategory and an observer for MagentoModelResourceModelCategoryFlat.



              Create a Module




              app/code/{vendor_name}/{module_name}




              Create




              app/code/{vendor_name}/{module_name}/registration.php




              MagentoFrameworkComponentComponentRegistrar::register(
              MagentoFrameworkComponentComponentRegistrar::MODULE,
              '{vendor_name}_{module_name}',
              __DIR__
              );



              app/code/{vendor_name}/{module_name}/etc/module.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
              <module name="{vendor_name}_{module_name}" setup_version="1.0.0"></module>
              </config>



              app/code/{vendor_name}/{module_name}/etc/di.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
              <preference for="MagentoCatalogModelResourceModelCategory" type="{vendor_name}{module_name}{path_to_class i.e ModelResourceModelCategory}" />
              </config>


              I've just used the same name as the file this is taking precedence over but this is optional.




              app/code/{vendor_name}/{module_name}ModelResourceModelCategory.php




              namespace {vendor_name}{module_name}ModelResourceModel;

              class Category extends MagentoCatalogModelResourceModelCategory
              {
              /* Override this method */

              public function getChildrenCategories($category)
              {
              $collection = $category->getCollection();
              /* @var $collection
              MagentoCatalogModelResourceModelCategoryCollection */
              $collection->addAttributeToSelect(
              'url_key'
              )->addAttributeToSelect(
              'name'
              )->

              /* Add this section to select image */
              addAttributeToSelect(
              'image'
              )->
              /* Add this section to select image */

              addAttributeToSelect(
              'all_children'
              )->addAttributeToSelect(
              'is_anchor'
              )->addAttributeToFilter(
              'is_active',
              1
              )->addIdFilter(
              $category->getChildren()
              )->setOrder(
              'position',
              MagentoFrameworkDBSelect::SQL_ASC
              )->joinUrlRewrite()->load();

              return $collection;
              }
              }


              Ideally I would have used a plugin here, but sadly because of how this method is defined I don't see how I can.



              I used Magento_Catalog/template/category/description.phtml to output my subcategories, I'm using the category main image as a thumbnail.



              <?php if ($_description = $_category->getDescription()): ?>
              <div class="category-description">
              <?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_category, $_description, 'description') ?>
              </div>
              <?php endif; ?>

              <?php if($_category->hasChildren()): ?>
              <div class="categories wrapper grid categories-grid">
              <ul class="categories list items categories-items">
              <?php foreach($_category->getChildrenCategories() as $_child): ?>
              <?php if($_child->getIsActive()): ?>
              <li class="item category category-item">
              <?php if($_child->getImageUrl()): ?> <!-- We can now use getImageUrl() on child categories -->
              <a href="<?php echo $_child->getUrl() ?>" class="category photo category-item-photo" tabindex="-1">
              <span class="category-image-container">
              <span class="category-image-wrapper" style="padding-bottom: 125%;">
              <img class="category-image-photo" src="<?php echo $_child->getImageUrl(); ?>" alt="<?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?>" />
              </span>
              </span>
              </a>
              <?php endif; ?>
              <strong class="category name category-item-name">
              <a class="category-item-link" href="<?php echo $_child->getUrl() ?>"><?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?></a>
              </strong>
              </li>
              <?php endif; ?>
              <?php endforeach; ?>
              </ul>
              </div>
              <?php endif; ?>


              This works great for EAV mode but doesn't work in flat category mode, to fix that we need to create an observer, oddly Magento provides a hook/event to modify the database query in flat category mode, but not in EAV mode.



              Create




              app/code/{vendor_name}/{module_name}/etc/frontend/events.xml




              I've used frontend here as I'm only interested in observing this event on the frontend.



              <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="{uour_unique_observer_name}" instance="{vendor_name}/{module_name}/Observer/{Whatever i.e CategoryFlatObserver}" />
              </event>




              Finally an observer class




              app/code/{vendor_name}/{module_name}/Observer/{your_observer_name




              i.e FlatCategoryObserver.php}`



              namespace {vendor_name}{module_name}Observer;

              use MagentoFrameworkEventObserverInterface;

              class CategoryFlatObserver implements ObserverInterface
              {
              public function execute(MagentoFrameworkEventObserver $observer)
              {
              $select = $observer->getData('select');
              $select->columns('image');
              }
              }


              Now anywhere the category resource model and getChildrenCategories() method is used on the frontend it will select the category image. Need to do a setup:upgrade and clear all caches before this will work.






              share|improve this answer


























              • Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

                – Octoxan
                Feb 28 '18 at 15:44











              • @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

                – 4D1
                Apr 6 '18 at 14:35


















              0














              I did this by creating a preference for MagentoModelResourceModelCategory and an observer for MagentoModelResourceModelCategoryFlat.



              Create a Module




              app/code/{vendor_name}/{module_name}




              Create




              app/code/{vendor_name}/{module_name}/registration.php




              MagentoFrameworkComponentComponentRegistrar::register(
              MagentoFrameworkComponentComponentRegistrar::MODULE,
              '{vendor_name}_{module_name}',
              __DIR__
              );



              app/code/{vendor_name}/{module_name}/etc/module.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
              <module name="{vendor_name}_{module_name}" setup_version="1.0.0"></module>
              </config>



              app/code/{vendor_name}/{module_name}/etc/di.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
              <preference for="MagentoCatalogModelResourceModelCategory" type="{vendor_name}{module_name}{path_to_class i.e ModelResourceModelCategory}" />
              </config>


              I've just used the same name as the file this is taking precedence over but this is optional.




              app/code/{vendor_name}/{module_name}ModelResourceModelCategory.php




              namespace {vendor_name}{module_name}ModelResourceModel;

              class Category extends MagentoCatalogModelResourceModelCategory
              {
              /* Override this method */

              public function getChildrenCategories($category)
              {
              $collection = $category->getCollection();
              /* @var $collection
              MagentoCatalogModelResourceModelCategoryCollection */
              $collection->addAttributeToSelect(
              'url_key'
              )->addAttributeToSelect(
              'name'
              )->

              /* Add this section to select image */
              addAttributeToSelect(
              'image'
              )->
              /* Add this section to select image */

              addAttributeToSelect(
              'all_children'
              )->addAttributeToSelect(
              'is_anchor'
              )->addAttributeToFilter(
              'is_active',
              1
              )->addIdFilter(
              $category->getChildren()
              )->setOrder(
              'position',
              MagentoFrameworkDBSelect::SQL_ASC
              )->joinUrlRewrite()->load();

              return $collection;
              }
              }


              Ideally I would have used a plugin here, but sadly because of how this method is defined I don't see how I can.



              I used Magento_Catalog/template/category/description.phtml to output my subcategories, I'm using the category main image as a thumbnail.



              <?php if ($_description = $_category->getDescription()): ?>
              <div class="category-description">
              <?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_category, $_description, 'description') ?>
              </div>
              <?php endif; ?>

              <?php if($_category->hasChildren()): ?>
              <div class="categories wrapper grid categories-grid">
              <ul class="categories list items categories-items">
              <?php foreach($_category->getChildrenCategories() as $_child): ?>
              <?php if($_child->getIsActive()): ?>
              <li class="item category category-item">
              <?php if($_child->getImageUrl()): ?> <!-- We can now use getImageUrl() on child categories -->
              <a href="<?php echo $_child->getUrl() ?>" class="category photo category-item-photo" tabindex="-1">
              <span class="category-image-container">
              <span class="category-image-wrapper" style="padding-bottom: 125%;">
              <img class="category-image-photo" src="<?php echo $_child->getImageUrl(); ?>" alt="<?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?>" />
              </span>
              </span>
              </a>
              <?php endif; ?>
              <strong class="category name category-item-name">
              <a class="category-item-link" href="<?php echo $_child->getUrl() ?>"><?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?></a>
              </strong>
              </li>
              <?php endif; ?>
              <?php endforeach; ?>
              </ul>
              </div>
              <?php endif; ?>


              This works great for EAV mode but doesn't work in flat category mode, to fix that we need to create an observer, oddly Magento provides a hook/event to modify the database query in flat category mode, but not in EAV mode.



              Create




              app/code/{vendor_name}/{module_name}/etc/frontend/events.xml




              I've used frontend here as I'm only interested in observing this event on the frontend.



              <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="{uour_unique_observer_name}" instance="{vendor_name}/{module_name}/Observer/{Whatever i.e CategoryFlatObserver}" />
              </event>




              Finally an observer class




              app/code/{vendor_name}/{module_name}/Observer/{your_observer_name




              i.e FlatCategoryObserver.php}`



              namespace {vendor_name}{module_name}Observer;

              use MagentoFrameworkEventObserverInterface;

              class CategoryFlatObserver implements ObserverInterface
              {
              public function execute(MagentoFrameworkEventObserver $observer)
              {
              $select = $observer->getData('select');
              $select->columns('image');
              }
              }


              Now anywhere the category resource model and getChildrenCategories() method is used on the frontend it will select the category image. Need to do a setup:upgrade and clear all caches before this will work.






              share|improve this answer


























              • Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

                – Octoxan
                Feb 28 '18 at 15:44











              • @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

                – 4D1
                Apr 6 '18 at 14:35
















              0












              0








              0







              I did this by creating a preference for MagentoModelResourceModelCategory and an observer for MagentoModelResourceModelCategoryFlat.



              Create a Module




              app/code/{vendor_name}/{module_name}




              Create




              app/code/{vendor_name}/{module_name}/registration.php




              MagentoFrameworkComponentComponentRegistrar::register(
              MagentoFrameworkComponentComponentRegistrar::MODULE,
              '{vendor_name}_{module_name}',
              __DIR__
              );



              app/code/{vendor_name}/{module_name}/etc/module.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
              <module name="{vendor_name}_{module_name}" setup_version="1.0.0"></module>
              </config>



              app/code/{vendor_name}/{module_name}/etc/di.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
              <preference for="MagentoCatalogModelResourceModelCategory" type="{vendor_name}{module_name}{path_to_class i.e ModelResourceModelCategory}" />
              </config>


              I've just used the same name as the file this is taking precedence over but this is optional.




              app/code/{vendor_name}/{module_name}ModelResourceModelCategory.php




              namespace {vendor_name}{module_name}ModelResourceModel;

              class Category extends MagentoCatalogModelResourceModelCategory
              {
              /* Override this method */

              public function getChildrenCategories($category)
              {
              $collection = $category->getCollection();
              /* @var $collection
              MagentoCatalogModelResourceModelCategoryCollection */
              $collection->addAttributeToSelect(
              'url_key'
              )->addAttributeToSelect(
              'name'
              )->

              /* Add this section to select image */
              addAttributeToSelect(
              'image'
              )->
              /* Add this section to select image */

              addAttributeToSelect(
              'all_children'
              )->addAttributeToSelect(
              'is_anchor'
              )->addAttributeToFilter(
              'is_active',
              1
              )->addIdFilter(
              $category->getChildren()
              )->setOrder(
              'position',
              MagentoFrameworkDBSelect::SQL_ASC
              )->joinUrlRewrite()->load();

              return $collection;
              }
              }


              Ideally I would have used a plugin here, but sadly because of how this method is defined I don't see how I can.



              I used Magento_Catalog/template/category/description.phtml to output my subcategories, I'm using the category main image as a thumbnail.



              <?php if ($_description = $_category->getDescription()): ?>
              <div class="category-description">
              <?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_category, $_description, 'description') ?>
              </div>
              <?php endif; ?>

              <?php if($_category->hasChildren()): ?>
              <div class="categories wrapper grid categories-grid">
              <ul class="categories list items categories-items">
              <?php foreach($_category->getChildrenCategories() as $_child): ?>
              <?php if($_child->getIsActive()): ?>
              <li class="item category category-item">
              <?php if($_child->getImageUrl()): ?> <!-- We can now use getImageUrl() on child categories -->
              <a href="<?php echo $_child->getUrl() ?>" class="category photo category-item-photo" tabindex="-1">
              <span class="category-image-container">
              <span class="category-image-wrapper" style="padding-bottom: 125%;">
              <img class="category-image-photo" src="<?php echo $_child->getImageUrl(); ?>" alt="<?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?>" />
              </span>
              </span>
              </a>
              <?php endif; ?>
              <strong class="category name category-item-name">
              <a class="category-item-link" href="<?php echo $_child->getUrl() ?>"><?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?></a>
              </strong>
              </li>
              <?php endif; ?>
              <?php endforeach; ?>
              </ul>
              </div>
              <?php endif; ?>


              This works great for EAV mode but doesn't work in flat category mode, to fix that we need to create an observer, oddly Magento provides a hook/event to modify the database query in flat category mode, but not in EAV mode.



              Create




              app/code/{vendor_name}/{module_name}/etc/frontend/events.xml




              I've used frontend here as I'm only interested in observing this event on the frontend.



              <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="{uour_unique_observer_name}" instance="{vendor_name}/{module_name}/Observer/{Whatever i.e CategoryFlatObserver}" />
              </event>




              Finally an observer class




              app/code/{vendor_name}/{module_name}/Observer/{your_observer_name




              i.e FlatCategoryObserver.php}`



              namespace {vendor_name}{module_name}Observer;

              use MagentoFrameworkEventObserverInterface;

              class CategoryFlatObserver implements ObserverInterface
              {
              public function execute(MagentoFrameworkEventObserver $observer)
              {
              $select = $observer->getData('select');
              $select->columns('image');
              }
              }


              Now anywhere the category resource model and getChildrenCategories() method is used on the frontend it will select the category image. Need to do a setup:upgrade and clear all caches before this will work.






              share|improve this answer















              I did this by creating a preference for MagentoModelResourceModelCategory and an observer for MagentoModelResourceModelCategoryFlat.



              Create a Module




              app/code/{vendor_name}/{module_name}




              Create




              app/code/{vendor_name}/{module_name}/registration.php




              MagentoFrameworkComponentComponentRegistrar::register(
              MagentoFrameworkComponentComponentRegistrar::MODULE,
              '{vendor_name}_{module_name}',
              __DIR__
              );



              app/code/{vendor_name}/{module_name}/etc/module.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
              <module name="{vendor_name}_{module_name}" setup_version="1.0.0"></module>
              </config>



              app/code/{vendor_name}/{module_name}/etc/di.xml




              <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
              <preference for="MagentoCatalogModelResourceModelCategory" type="{vendor_name}{module_name}{path_to_class i.e ModelResourceModelCategory}" />
              </config>


              I've just used the same name as the file this is taking precedence over but this is optional.




              app/code/{vendor_name}/{module_name}ModelResourceModelCategory.php




              namespace {vendor_name}{module_name}ModelResourceModel;

              class Category extends MagentoCatalogModelResourceModelCategory
              {
              /* Override this method */

              public function getChildrenCategories($category)
              {
              $collection = $category->getCollection();
              /* @var $collection
              MagentoCatalogModelResourceModelCategoryCollection */
              $collection->addAttributeToSelect(
              'url_key'
              )->addAttributeToSelect(
              'name'
              )->

              /* Add this section to select image */
              addAttributeToSelect(
              'image'
              )->
              /* Add this section to select image */

              addAttributeToSelect(
              'all_children'
              )->addAttributeToSelect(
              'is_anchor'
              )->addAttributeToFilter(
              'is_active',
              1
              )->addIdFilter(
              $category->getChildren()
              )->setOrder(
              'position',
              MagentoFrameworkDBSelect::SQL_ASC
              )->joinUrlRewrite()->load();

              return $collection;
              }
              }


              Ideally I would have used a plugin here, but sadly because of how this method is defined I don't see how I can.



              I used Magento_Catalog/template/category/description.phtml to output my subcategories, I'm using the category main image as a thumbnail.



              <?php if ($_description = $_category->getDescription()): ?>
              <div class="category-description">
              <?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_category, $_description, 'description') ?>
              </div>
              <?php endif; ?>

              <?php if($_category->hasChildren()): ?>
              <div class="categories wrapper grid categories-grid">
              <ul class="categories list items categories-items">
              <?php foreach($_category->getChildrenCategories() as $_child): ?>
              <?php if($_child->getIsActive()): ?>
              <li class="item category category-item">
              <?php if($_child->getImageUrl()): ?> <!-- We can now use getImageUrl() on child categories -->
              <a href="<?php echo $_child->getUrl() ?>" class="category photo category-item-photo" tabindex="-1">
              <span class="category-image-container">
              <span class="category-image-wrapper" style="padding-bottom: 125%;">
              <img class="category-image-photo" src="<?php echo $_child->getImageUrl(); ?>" alt="<?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?>" />
              </span>
              </span>
              </a>
              <?php endif; ?>
              <strong class="category name category-item-name">
              <a class="category-item-link" href="<?php echo $_child->getUrl() ?>"><?php /* @escapeNotVerified */ echo $this->helper('MagentoCatalogHelperOutput')->categoryAttribute($_child, $_child->getName(), 'name') ?></a>
              </strong>
              </li>
              <?php endif; ?>
              <?php endforeach; ?>
              </ul>
              </div>
              <?php endif; ?>


              This works great for EAV mode but doesn't work in flat category mode, to fix that we need to create an observer, oddly Magento provides a hook/event to modify the database query in flat category mode, but not in EAV mode.



              Create




              app/code/{vendor_name}/{module_name}/etc/frontend/events.xml




              I've used frontend here as I'm only interested in observing this event on the frontend.



              <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="{uour_unique_observer_name}" instance="{vendor_name}/{module_name}/Observer/{Whatever i.e CategoryFlatObserver}" />
              </event>




              Finally an observer class




              app/code/{vendor_name}/{module_name}/Observer/{your_observer_name




              i.e FlatCategoryObserver.php}`



              namespace {vendor_name}{module_name}Observer;

              use MagentoFrameworkEventObserverInterface;

              class CategoryFlatObserver implements ObserverInterface
              {
              public function execute(MagentoFrameworkEventObserver $observer)
              {
              $select = $observer->getData('select');
              $select->columns('image');
              }
              }


              Now anywhere the category resource model and getChildrenCategories() method is used on the frontend it will select the category image. Need to do a setup:upgrade and clear all caches before this will work.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 6 '18 at 14:45

























              answered Oct 4 '17 at 17:23









              4D14D1

              1115




              1115













              • Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

                – Octoxan
                Feb 28 '18 at 15:44











              • @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

                – 4D1
                Apr 6 '18 at 14:35





















              • Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

                – Octoxan
                Feb 28 '18 at 15:44











              • @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

                – 4D1
                Apr 6 '18 at 14:35



















              Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

              – Octoxan
              Feb 28 '18 at 15:44





              Did all this and it's still returning null. Made sure I fixed all the broken code too (no php or xml opening tags and the missing endif in your description.phtml)

              – Octoxan
              Feb 28 '18 at 15:44













              @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

              – 4D1
              Apr 6 '18 at 14:35







              @Octoxan no need for that tone, I copied and pasted this from my file, I must have missed copying the the final endif in description. The rest of it is intentional, anyone wanting to mess around with the code should know they need PHP and XML tags. I assume you changed all of the {vendor_name}/{module_name} instances to whatever yours is? Did you do setup:upgrade to register the new module and clear cache etc.

              – 4D1
              Apr 6 '18 at 14:35













              0














              If you are still looking for a solution to show Subcategories on parent category page. Have a look at Advanced Subcategory Grid module on Magento2 Marketplace that can be used to show subcategories on category pages, its highly customizable and also supports configurable color swatches as-well.






              share|improve this answer




























                0














                If you are still looking for a solution to show Subcategories on parent category page. Have a look at Advanced Subcategory Grid module on Magento2 Marketplace that can be used to show subcategories on category pages, its highly customizable and also supports configurable color swatches as-well.






                share|improve this answer


























                  0












                  0








                  0







                  If you are still looking for a solution to show Subcategories on parent category page. Have a look at Advanced Subcategory Grid module on Magento2 Marketplace that can be used to show subcategories on category pages, its highly customizable and also supports configurable color swatches as-well.






                  share|improve this answer













                  If you are still looking for a solution to show Subcategories on parent category page. Have a look at Advanced Subcategory Grid module on Magento2 Marketplace that can be used to show subcategories on category pages, its highly customizable and also supports configurable color swatches as-well.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 19 mins ago









                  Saad TaimoorSaad Taimoor

                  694




                  694























                      -1














                      I have Put Below Code Magento_Catalog/templates/category/products.phtml File and Get all Subcategory Images and Data.



                      $_helper    = $this->helper('MagentoCatalogHelperOutput');
                      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                      $category = $objectManager->get('MagentoFrameworkRegistry')->registry('current_category');
                      $childcategories = $category->getChildrenCategories();
                      $sub_category_count = count($childcategories);

                      if($sub_category_count != 0){
                      echo '<ul>';
                      foreach($childcategories as $child)
                      {
                      echo '<li class="sub-cat">';
                      $cat = $objectManager->create('MagentoCatalogModelCategory')->load($child->getId());

                      if ($_imgUrl = $cat->getImageUrl())
                      {
                      $_imgHtml = '<div class="category-image"><img src="' . $_imgUrl . '" alt="' . $block->escapeHtml($cat->getName()) . '" title="' . $block->escapeHtml($cat->getName()) . '" class="image" /></div>';
                      $_imgHtml = $_helper->categoryAttribute($cat, $_imgHtml, 'image');
                      /* @escapeNotVerified */ echo $_imgHtml;
                      }

                      echo '</li>'; }
                      echo '</ul>';
                      } else {
                      if (!$block->isContentMode() || $block->isMixedMode()):
                      echo $block->getProductListHtml();
                      endif;
                      }


                      It's Working Fine for me.






                      share|improve this answer
























                      • You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

                        – Vlad Patru
                        Apr 6 '17 at 20:57











                      • Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

                        – Toan Nguyen
                        Aug 14 '17 at 4:58
















                      -1














                      I have Put Below Code Magento_Catalog/templates/category/products.phtml File and Get all Subcategory Images and Data.



                      $_helper    = $this->helper('MagentoCatalogHelperOutput');
                      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                      $category = $objectManager->get('MagentoFrameworkRegistry')->registry('current_category');
                      $childcategories = $category->getChildrenCategories();
                      $sub_category_count = count($childcategories);

                      if($sub_category_count != 0){
                      echo '<ul>';
                      foreach($childcategories as $child)
                      {
                      echo '<li class="sub-cat">';
                      $cat = $objectManager->create('MagentoCatalogModelCategory')->load($child->getId());

                      if ($_imgUrl = $cat->getImageUrl())
                      {
                      $_imgHtml = '<div class="category-image"><img src="' . $_imgUrl . '" alt="' . $block->escapeHtml($cat->getName()) . '" title="' . $block->escapeHtml($cat->getName()) . '" class="image" /></div>';
                      $_imgHtml = $_helper->categoryAttribute($cat, $_imgHtml, 'image');
                      /* @escapeNotVerified */ echo $_imgHtml;
                      }

                      echo '</li>'; }
                      echo '</ul>';
                      } else {
                      if (!$block->isContentMode() || $block->isMixedMode()):
                      echo $block->getProductListHtml();
                      endif;
                      }


                      It's Working Fine for me.






                      share|improve this answer
























                      • You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

                        – Vlad Patru
                        Apr 6 '17 at 20:57











                      • Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

                        – Toan Nguyen
                        Aug 14 '17 at 4:58














                      -1












                      -1








                      -1







                      I have Put Below Code Magento_Catalog/templates/category/products.phtml File and Get all Subcategory Images and Data.



                      $_helper    = $this->helper('MagentoCatalogHelperOutput');
                      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                      $category = $objectManager->get('MagentoFrameworkRegistry')->registry('current_category');
                      $childcategories = $category->getChildrenCategories();
                      $sub_category_count = count($childcategories);

                      if($sub_category_count != 0){
                      echo '<ul>';
                      foreach($childcategories as $child)
                      {
                      echo '<li class="sub-cat">';
                      $cat = $objectManager->create('MagentoCatalogModelCategory')->load($child->getId());

                      if ($_imgUrl = $cat->getImageUrl())
                      {
                      $_imgHtml = '<div class="category-image"><img src="' . $_imgUrl . '" alt="' . $block->escapeHtml($cat->getName()) . '" title="' . $block->escapeHtml($cat->getName()) . '" class="image" /></div>';
                      $_imgHtml = $_helper->categoryAttribute($cat, $_imgHtml, 'image');
                      /* @escapeNotVerified */ echo $_imgHtml;
                      }

                      echo '</li>'; }
                      echo '</ul>';
                      } else {
                      if (!$block->isContentMode() || $block->isMixedMode()):
                      echo $block->getProductListHtml();
                      endif;
                      }


                      It's Working Fine for me.






                      share|improve this answer













                      I have Put Below Code Magento_Catalog/templates/category/products.phtml File and Get all Subcategory Images and Data.



                      $_helper    = $this->helper('MagentoCatalogHelperOutput');
                      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                      $category = $objectManager->get('MagentoFrameworkRegistry')->registry('current_category');
                      $childcategories = $category->getChildrenCategories();
                      $sub_category_count = count($childcategories);

                      if($sub_category_count != 0){
                      echo '<ul>';
                      foreach($childcategories as $child)
                      {
                      echo '<li class="sub-cat">';
                      $cat = $objectManager->create('MagentoCatalogModelCategory')->load($child->getId());

                      if ($_imgUrl = $cat->getImageUrl())
                      {
                      $_imgHtml = '<div class="category-image"><img src="' . $_imgUrl . '" alt="' . $block->escapeHtml($cat->getName()) . '" title="' . $block->escapeHtml($cat->getName()) . '" class="image" /></div>';
                      $_imgHtml = $_helper->categoryAttribute($cat, $_imgHtml, 'image');
                      /* @escapeNotVerified */ echo $_imgHtml;
                      }

                      echo '</li>'; }
                      echo '</ul>';
                      } else {
                      if (!$block->isContentMode() || $block->isMixedMode()):
                      echo $block->getProductListHtml();
                      endif;
                      }


                      It's Working Fine for me.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 7 '16 at 7:17









                      NikulNikul

                      691918




                      691918













                      • You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

                        – Vlad Patru
                        Apr 6 '17 at 20:57











                      • Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

                        – Toan Nguyen
                        Aug 14 '17 at 4:58



















                      • You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

                        – Vlad Patru
                        Apr 6 '17 at 20:57











                      • Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

                        – Toan Nguyen
                        Aug 14 '17 at 4:58

















                      You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

                      – Vlad Patru
                      Apr 6 '17 at 20:57





                      You should never use obhectManager in phtml directly. A better sollution is to create s simple custom module and create all the needed functionality in the block itself, and after that call the block in catalog_category_view.xml

                      – Vlad Patru
                      Apr 6 '17 at 20:57













                      Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

                      – Toan Nguyen
                      Aug 14 '17 at 4:58





                      Please follow the coding standards of Magento 2. FYI devdocs.magento.com/guides/v2.1/coding-standards/…

                      – Toan Nguyen
                      Aug 14 '17 at 4:58


















                      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%2f120977%2fmagento-2-how-to-get-subcategory-image-in-category-page%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...