Magento 2 how to get all categories of a product in controller
-
13-03-2021 - |
Question
I am trying to get all categories with their levels of a product through it's ID in my controller which is overriding default magento controller.
Can I get product's category path url through it's id in controller ?
How can I do this?
No correct solution
OTHER TIPS
Try like this,
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$productId = 10001; // YOUR PRODUCT ID
$product = $productRepository->getById($productId);
$categoryIds = $product->getCategoryIds();
$categories = $categoryCollection->create()
->addAttributeToSelect('*')
->addAttributeToFilter('entity_id', $categoryIds);
foreach ($categories as $category) {
echo $category->getName() . '<br>';
}
Try below code :
protected $_productCollectionFactory;
protected $_categoryFactory;
protected $_productRepository;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Framework\ObjectManagerInterface $objectManager,
......... Add other depedencies
) {
$this->_productRepository = $productRepository;
$this->_categoryFactory = $categoryFactory;
$this->_productCollectionFactory = $productCollectionFactory;
$this->_objectManager = $objectManager;
......... Add other depedencies
}
public function execute()
{
$mainProduct = $this->getProductById($productId);
$categoryIds = $mainProduct->getCategoryIds();
$result = [];
for ($i=0; $i < count($categoryIds); $i++) {
$eachCat = [
"id" => $categoryIds[$i],
"name" => $this->getCategoryName($categoryIds[$i])
];
array_push($result, $eachCat);
}
return $result;
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getCategoryName($categoryId)
{
$category = $this->_objectManagerr->create('Magento\Catalog\Model\Category')->load($categoryId);
return $category->getName();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange