Search code examples
magentomagento-1.7

how to get immediate parent category from a product


i want to get immediate parent category from a current product, i have refereed

Get a product's parent category even if it is accessed directly

but it doesn't help me to find immediate parent category.

please help me

Thank You in Advance


Solution

  • If you have the product as an object, for this example we say your product object is $product. The following should work:

    $product->getCategory()->getParentCategory();
    

    That should return the parent category as an object of Mage_Catalog_Model_Category.

    If you don't have the product but say have the product id then the following should be enough to get the product.

    $product = Mage::getModel('catalog/product')->load($product_id);
    

    But note that a product could have more than one category assigned to in.

    If you have more than one category per product you can use getCategoryCollection() to get all the categories.

    foreach ($product->getCategoryCollection() as $category) {
        $parent_category = $category->getParentCategory();
    }