cancel
Showing results for 
Search instead for 
Did you mean: 

Get top level category from product template

SOLVED

Get top level category from product template

I would like to get top level category ID from a product page.

 

Top Category 1

        ---------------------  Child 1

        ---------------------  Child 2

                                   --------------- Grand Child 1   --------- product 1

 Top Category 2     

        ---------------------  Child 3

        ---------------------  Child 4

 

I would like to write a PHP condition such as "If this product is in Top Category 1".

 

 

 

Thanks in advance.

 

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Get top level category from product template

Hello @tvgarden 

 

If you want only category IDs please check below code for check all category IDs of that product.

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $_objectManager->get('\Magento\Catalog\Model\ProductRepository');
$productId = 1; // YOUR PRODUCT ID
$product = $productRepository->getById($productId);
$categoryIds = $product->getCategoryIds();

$categoryIds print and find your ID.

 

If you want the level of those ID please add below code.

 

$categoryCollection = $_objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryCollection->create()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', $categoryIds); 
print_r($categories->getData());

You can find out your categories level.

If you got a solution, please Accept as Solution & Click Kudos.

 

View solution in original post

1 REPLY 1

Re: Get top level category from product template

Hello @tvgarden 

 

If you want only category IDs please check below code for check all category IDs of that product.

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $_objectManager->get('\Magento\Catalog\Model\ProductRepository');
$productId = 1; // YOUR PRODUCT ID
$product = $productRepository->getById($productId);
$categoryIds = $product->getCategoryIds();

$categoryIds print and find your ID.

 

If you want the level of those ID please add below code.

 

$categoryCollection = $_objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryCollection->create()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', $categoryIds); 
print_r($categories->getData());

You can find out your categories level.

If you got a solution, please Accept as Solution & Click Kudos.