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

AmitTank picture AmitTank · Jul 28, 2016 · Viewed 22.6k times · Source

Hello I am new to magento2

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

Thanks in advance

Answer

Manashvi Birla picture Manashvi Birla · Aug 1, 2016

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;
    }
}