You need to instantiate Magento\Catalog\Model\ProductCategoryList class in your __construct() method to get category ids for a product. Here 5 and 12 is category id of the product with id is 10. The result will be an array of category ids for the products.
Using the source link dropped by Rao above I actually found a better answer:
$product = Mage::getModel('catalog/product')->load($productId);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
echo $_cat->getName();
}
This is utterly not tested..
//load the product
$product = Mage::getModel('catalog/product')->load($productId);
//load the categories of this product
$categoryCollection = $product->getCategoryCollection();
You can then loop through $categoryCollection
like through an array.
source
Want to point out that the solution by @Rao is the best if you have a product object to get category ID's from as it makes only one SQL call.
If you just have category id's, you can do the following:
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name') //you can add more attributes using this
->addAttributeToFilter('entity_id', array('in'=>array(1,2,3)));
foreach($categories as $_cat){
$holder[]= $_cat->getName();
}
Where array(1,2,3) are your categories. Note that the array has integers, not string values, I found that SQL can be picky about that.
Also wanted to point out that solutions pulling one category at a time are very inefficient as it makes an SQL call for every iteration of the loop e.g.:
foreach(..){
Mage::getModel('catalog/category')->load($categoryId);
}
Get all Categories of the Product
<?php
$_Product = Mage::getModel("catalog/product")->load( PRODUCT_ID );
$categoryIds = $_Product->getCategoryIds();//array of product categories
foreach($categoryIds as $categoryId) {
$category = Mage::getModel('catalog/category')->load($categoryId);
$this->_setAttribute('product_type', $category->getName(), 'text' );
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With