0

In my Magento 2.1 store, I need to display the categories that a product belongs to, in the attributes area of the page (Manufacturer, SKU, etc).

In my magento 1 store, I did this: https://stackoverflow.com/questions/9531702/magento-display-all-categories-on-product-view-page-with-parent-categories/9533005

So if a product is in two categories, they might be displayed as follows:

Root Cat > Sub Cat > Sub Sub Cat 1
Root Cat > Sub Cat > Sub Sub Cat 2

With each category level being clickable to go to that category.

How do I do the same thing in Magento 2.1?

1
  • Trying to get this to work in Magento 2.4.6.. Any suggestions?
    – Imco
    Commented Mar 3 at 20:49

1 Answer 1

1

For this first let's create new tab for category display.

  1. Create file catalog_product_view.xml in the

app/design/frontend/{vender name}/{theme name}/Magento_Catalog/layout

In the file write the below code:

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>      
        <referenceBlock name="product.info.details">
          <block class="Magento\Catalog\Block\Product\View" name="categoryinfo.tab" as="categoryinfo" template="product/view/category_info.phtml" group="detailed_info" >
             <arguments>
                <argument translate="true" name="title" xsi:type="string">Category</argument>
             </arguments>
          </block>
        </referenceBlock>
    </body>
</page>
  1. create the file category_info.phtml in the path

app/design/frontend/{vender name}/{theme name}/Magento_Catalog/templates/product/view.

In the file you can write any content like i have call all categories of this product.

    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

    $categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
    $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');

    $productId = $block->getProduct()->getId(); // YOUR PRODUCT ID
    $product = $productRepository->getById($productId);

    $categoryIds = $product->getCategoryIds();

    $categories = $categoryCollection->create()
                                     ->addAttributeToSelect('*')
                                     ->addAttributeToFilter('entity_id', $categoryIds);

    foreach ($categories as $category) {
        $name = $category->getName();
        $parentCategories = $category->getParentCategories();
     foreach($parentCategories as $parent){
       $parentname = $parent->getName();
       echo '<a href="'.$parent->getUrl().'" title="'.$parentname.'" alt="'.$parentname.'">';
       echo '<div>'.$parentname.'</div>';
       echo '</a>'; echo ' > ';
    }
echo '<a href="'.$category->getUrl().'" title="'.$name.'" alt="'.$name.'">';
echo '<div>'.$name.'</div>';
echo '</a>';
  if($category->hasChildren()) {
     $subcategories = $category->getChildrenCategories();
     foreach($subcategories as $subcat){
       $subname = $subcat->getName();
       echo ' > ';
      echo '<a href="'.$subcat->getUrl().'" title="'.$subname.'" alt="'.$subname.'">';
       echo '<div>'.$subname.'</div>';
      echo '</a>';
    }
  }
}
1
  • Thanks for this! I already had the display side of the code worked out from my Magento1 store, but the creation of the collections was the problem for me. Your code gave me the answer, and it works well! Rather oddly though, my old code to output the last item in the category breadcrumbs is no longer needed. Perhaps the "parent categories" also contains the category, and not just the parents, because everything is output correctly. Anyway - thank you!! :-)
    – robgt
    Commented Jun 13, 2017 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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