Magento 2: How to Get Subcategory Image in Category Page?
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
add a comment |
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
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
add a comment |
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
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
catalog image magento-2.0 category-view
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
add a comment |
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
add a comment |
4 Answers
4
active
oldest
votes
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;
}
}
add a comment |
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.
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
add a comment |
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.
add a comment |
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.
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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;
}
}
add a comment |
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;
}
}
add a comment |
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;
}
}
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;
}
}
edited Apr 6 '17 at 21:31
answered Apr 6 '17 at 21:01
Vlad PatruVlad Patru
848416
848416
add a comment |
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered 18 mins ago
Saad TaimoorSaad Taimoor
694
694
add a comment |
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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