ex: I have category list as follows:
Men
--top
---shoes
--bottom
I have current_category is shoes. so how to add class to this and all parent of this.
2 Answers
Using below code you can get parents of current category
<?php
/* $block \Magento\Catalog\Block\Category\View */
foreach ($block->getCurrentCategory()->getParentCategories() as $parent) {
echo $parent->getId();
}
?>
-
This code for category is working and is bringing all the categories of that product but if i want to target the Men CategoryID only. how to do that. Not other subcategories.– ZeeshanApr 24, 2019 at 10:43
Create Block and extended \Magento\Catalog\Block\Category\View
For Example
namespace Companyname\Categorylist\Block\Category;
use Magento\Framework\View\Element\Template;
class View extends \Magento\Catalog\Block\Category\View
{
protected $_coreRegistry = null;
public function __construct(
Template\Context $context,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
\Magento\Framework\Registry $registry,
\Magento\Catalog\Helper\Category $categoryHelper,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = array())
{
parent::__construct($context, $layerResolver, $registry, $categoryHelper,$data);
$this->_categoryFactory = $categoryFactory;
}
public function getCategoryList()
{
$_category = $this->getCurrentCategory();
$collection = $this->_categoryFactory->create()->getCollection()->addAttributeToSelect('*')
->addAttributeToFilter('is_active', 1)
->setOrder('position', 'ASC')
->addIdFilter($_category->getChildren());
return $collection;
}