Hello I am new to magento2
I want to get category name from specified category id Can anybody help ?
Thanks in advance
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;
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With