0

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.

1
  • what you want to do for category, have you want current category's all parent category id? Feb 29, 2016 at 7:03

2 Answers 2

5

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();
}
?>
1
  • 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.
    – Zeeshan
    Apr 24, 2019 at 10:43
0

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;

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.