Monday, 1 July 2019

Category Name instead of category ids in category path magento2.

protected $_categoryFactory;

public function __construct(
        \Magento\Catalog\Model\CategoryFactory $categoryFactory
    ) {
        $this->_categoryFactory = $categoryFactory;
        parent::__construct($context);
    }



public function getCategoryInfo(){

     $categoryItem = $this->_categoryFactory->create();
     $categoryItem->load(5); // 5 is category id
    echo  $categoy_name_from_path = $this->getCategoryFromPath($categoryItem->getPath());

}

 public function getCategoryFromPath($pathIds){
  $name='';
  $path = explode('/', $pathIds);
          foreach ($path as $pathId)
{
$category = $this->_categoryFactory->create();
$category->load($pathId);
$name.=$category->getName().' / ';
}
return rtrim(ltrim($name, ' / '), ' / ');
             // output will be like as  Default Category / first child category / sec child category / third child category  
}


No comments:

Post a Comment