Root Category (id: 1)
- Apparel (id: 2)
-- Shirts (id:4)
-- Pants (id:5)
- Accessories (id: 3)
-- Handbags (id:6)
-- Jewelry (id:7)
On Magento we can get the category Ids of a product by using $productObj->getCategoryIds()
$productObj = Mage::getModel('catalog/product')->load($product_id);
$categoryIds = $productObj->getCategoryIds();
Which will return an array of category Ids of the product. I have a specific need to get the first level parent of category of a product. Takes for example the category tree above, if a product is categorized in Pants category, I want to get the first level category which is Apparel (in this case, the product only tagged under Pants category but not tagged in Apparel category).
Question: what method can I use to get the parent category of a sub category, or is it possible to get the first level category from a product?
You can use the catalog/category
model and its method getParentCategory()
:
foreach ($categoryIds as $iCategoryId) {
$m = Mage::getModel('catalog/category')
->load($iCategoryId)
->getParentCategory();
var_dump($m->debug());
}
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