Magento – Magento2 Get Category Id like breadcrumbs of Current Product

breadcrumbscategorymagento2product

If product belongs to Blue-Shirt(may be Shirt also). and category and tree is like

-Root(Id-2)
 -Shirt (Id-35)
  -Blue-Shirt(Id-36)

I want to get category ID like breadcrumbs 1/2/35/36
.May be i can get it from breadcrumbs somewhere?

enter image description here

Best Answer

Try below code snippet to your product/view/details.phtml

<div>
    <?php
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
        $categoryIds = $product->getCategoryIds();
        $categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');

        $categories = $categoryFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', $categoryIds)->setOrder('position', 'ASC'); ?>
        <ul class="items">
        <?php

        foreach ($categories as $category){?>
             <li class="item" style="display:inline;"><?php
            echo $category->getName()."(".$category->getId().")";
         ?>
            </li>
            <?php echo "/";} 

    ?> 
    </div>

This will display all the assigned categories to the products Like,

Default Category(2) / All Products(9) / Fashion(4) / Fragrance(6)

Likewise you can get the value of you category attribute and display it here.