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.
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.
$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
$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!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply