In this post I am going to explain how to get all categories of specific product in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | protected $_categoryCollectionFactory; protected $_productRepository; public function __construct( \Magento\Catalog\Block\Product\Context $context, \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory, \Magento\Catalog\Model\ProductRepository $productRepository, array $data = [] ) { $this->_categoryCollectionFactory = $categoryCollectionFactory; $this->_productRepository = $productRepository; parent::__construct($context, $data); } public function getProductCategoryIds($productId) { $product = $this->_productRepository->getById($productId); $productCategoryIds = $product->getCategoryIds(); return $productCategoryIds; } public function getProductCategoriesCollection($categoryIds) { $categoryCollection = $this->_categoryCollectionFactory->create(); $categoryCollection->addAttributeToSelect('*'); $categoryCollection->addIsActiveFilter(); $categoryCollection->addAttributeToFilter('entity_id', $categoryIds); return $categoryCollection; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $productId = 1; // get product categorory ids $productCategoryIds = $block->getProductCategoryIds($productId); echo "<pre>"; print_r($productCategoryIds); echo "</pre>"; // get product category collection $categoryCollection = $block->getProductCategoriesCollection($productCategoryIds); if ($categoryCollection && count($categoryCollection) > 0) { foreach ($categoryCollection as $category) { echo $category->getId() . '<br>'; echo $category->getName() . '<br>'; echo $category->getUrl() . '<br>'; } } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository'); $categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory'); $productId = 1; $product = $productRepository->getById($productId); // get product categorory ids $productCategoryIds = $product->getCategoryIds(); echo "<pre>"; print_r($productCategoryIds); echo "</pre>"; // get product category collection $categoryCollection = $categoryCollection->create(); $categoryCollection->addAttributeToSelect('*'); $categoryCollection->addAttributeToFilter('entity_id', $productCategoryIds); if ($categoryCollection && count($categoryCollection) > 0) { foreach ($categoryCollection as $category) { echo $category->getId() . '<br>'; echo $category->getName() . '<br>'; echo $category->getUrl() . '<br>'; } } |
Thats it. Enjoy Magento 2!!
Leave a Reply