Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento How to get The Parent Category of A Sub-Category from A Product

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?

like image 547
Calua Avatar asked Feb 22 '12 09:02

Calua


1 Answers

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());
}
like image 176
Jürgen Thelen Avatar answered Nov 15 '22 09:11

Jürgen Thelen