3

Want to display the category name for each product in new products widget and best sellers widget

I have tried this but not working

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
echo $category->getname();
5
  • Hiii TRy my secound method Jan 17 '18 at 12:20
  • Replace $category->getname() BY echo $category->getName(); Jan 17 '18 at 12:21
  • Thanks. but still not working.
    – Rathna
    Jan 17 '18 at 12:50
  • using registry to get current category doesn't work on 2.2.x
    – Sylvester
    Aug 13 '18 at 10:26
  • then which one works? Feb 17 '20 at 10:59
3
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product       = $objectManager->create('Magento\Catalog\Model\Product')->load($_item->getId());
$categories    = $product->getCategoryIds();
$cat_name      = array();
foreach ($categories as $category) {
    $cat        = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
    $cat_name[] = $cat->getName();
}
echo "<pre/>";
print_r($cat_name);
6
  • Not working.Have added this same code under templates\product\widget\content\grid.phtml.
    – Rathna
    Jan 17 '18 at 12:49
  • have you modify 2 line as per product collection
    – Kushal
    Jan 17 '18 at 12:55
  • $product = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId()); here you have to pass your product id
    – Kushal
    Jan 17 '18 at 13:01
  • can you help me to getproduct id
    – Rathna
    Jan 17 '18 at 13:10
  • I have updated the answer, please try again
    – Kushal
    Jan 17 '18 at 13:22
2

Try This

  <?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
    echo $category->getId();
    echo $category->getName();
?>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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