Jul 21, 2013
kalpesh

Magento get all categories of a product

Get all the categories a product belongs to in Magento. Below code will get you all the categories with details the product is attached to. Product can be shown under more than one category, so you may get more than one category ID. Either get the category collection from product, or get all the category IDs and then load them using catalog category collection model.

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

First way,

$catCollection = $_product->getCategoryCollection();
foreach($catCollection as $cat){
  print_r($cat->getData());
  //echo $cat->getName();
  //echo $cat->getUrl();
}

Another way,

$catIds = $_product->getCategoryIds();
$catCollection = Mage::getResourceModel('catalog/category_collection')
                     //->addAttributeToSelect('name')
                     //->addAttributeToSelect('url')
                     ->addAttributeToSelect('*')
                     ->addAttributeToFilter('entity_id', $catIds)
                     ->addIsActiveFilter();

foreach($catCollection as $cat){
  print_r($cat->getData());
  //echo $cat->getName();
  //echo $cat->getUrl();
}

3 Comments

  • How can I use your code in a multi-site setup.

    For example, Product X is in Site 1 / Cat x, Site 1 Cat y, Site 2 Cat z

    I want to display on Site 1 – cat x and cat y but not cat z

    And on Site 2 I want display cat z but not cat x or cat y.

    Thanks!

  • how to migrate the catalog database from one server to another server in magento

    Thanks

  • Thank you..

    but how can i get non layered category>

Leave a comment

 

Welcome to my Blog

Kalpesh MehtaHelping Magento developers in their day-to-day development problems since 2011. Most of the problems and solutions here are my own experiences while working on different projects. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications

Honor

Recognition

Magento top 50 contributors

Magento top 50 contributors

Contributions