1

I cant seem to get Category name while i can Get Id and URL am i doing something wrong?

Layout (catalog_product_view.xml)

<block class="Magento\Catalog\Block\Product\View" name="product.category" template="productCategory.phtml"/>

Template

<?php 
  $_product = $block->getProduct();
  $categoryCollection = $_product->getCategoryCollection();

  foreach ($categoryCollection as $value) {
      echo $value->getUrl(); // This returns correct Urls
      echo $value->getId(); //This return correct Ids
      echo $value->getName(); // This returns Null
  }
  ?>

EDIT

Have tried and not showing null

$value->getData()
$value->getPath()
$value->getParentCategory()->getName()

I'm finding this very confusing, as how i can return almost anything except name

Im doing this in magento 2.

2
  • Is this magento 2 or magento 1? Because it seems to be magento 1 Jun 10, 2016 at 13:15
  • @Andre its magento 2 i just want to show categories of current product on its page, so i tried to go with something simple
    – MePo
    Jun 10, 2016 at 14:27

1 Answer 1

4

You can do this:

$_product = $block->getProduct();
$categoryCollection = $_product->getCategoryCollection()
        ->addAttributeToSelect('name');

foreach ($categoryCollection as $value) {

      echo $value->getUrl(); // This returns correct Urls
      echo $value->getId(); //This return correct Ids
      echo $value->getName(); // Will return the proper name
}

This way you won't have to load anything in a loop.

2
  • 1
    Just a question why isnt the name included in Collection?
    – MePo
    Jun 13, 2016 at 5:31
  • 1
    In general, the sql query associated to a collection is executed only on the base table of the entity. In this case catalog_category_entity. For flat entities it retrieves every field, but for EAV collections you have to add the attributes you need by hand, to avoid performance issues. See how the getCategoryCollection method looks
    – Marius
    Jun 13, 2016 at 6:36

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.