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.
Solved! Go to Solution.
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.
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.