Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Category Name for specified Category id in phtml template - Magento2

Tags:

magento2

Hello I am new to magento2

I want to get category name from specified category id Can anybody help ?

Thanks in advance

like image 497
AmitTank Avatar asked Jul 28 '16 14:07

AmitTank


2 Answers

You should never use the ObjectManager.

You can put this in the Block, and call the function getCategoryName() in the phtml :

namespace Company\Module\Block;

class CustomBlock extends \Magento\Framework\View\Element\Template 
{
    protected $_categoryFactory;    

    public function __construct(
    \Magento\Catalog\Model\CategoryFactory $categoryFactory,
    \Magento\Framework\View\Element\Template\Context $context,
    ) {
        $this->_categoryFactory = $categoryFactory;
        parent::__construct($context);
    }

    public function getCategoryName()
    {
        $categoryId = '43';
        $category = $this->_categoryFactory->create()->load($categoryId);
        $categoryName = $category->getName();
        return $categoryName;
    }
}
like image 158
Manashvi Birla Avatar answered Sep 28 '22 18:09

Manashvi Birla


Try following code for getting Category Object in Magento2:

$categoryId = 3;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $_objectManager->create('Magento\Catalog\Model\Category')
->load($categoryId);
echo $category->getName();
like image 26
Emizen Tech Avatar answered Sep 28 '22 16:09

Emizen Tech