Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get product category information using collections in Magento

I am trying to output all the products from our Magento shop - the following code works, however I also need to grab the category id & the parent category name too. Can anyone suggest how I can do this?

$product = Mage::getModel('catalog/product'); 
$productCollection = $product->getCollection()
->addAttributeToSelect('*');


foreach ( $productCollection as $_product ) {
    echo $_product->getName().'<br/>';        
}
like image 588
Zabs Avatar asked Dec 18 '22 02:12

Zabs


1 Answers

In some instances $_product->getCategory() can return empty and cause an error.

A better solution is to fetch categories by ID:

$categoryIds = $_product->getCategoryIds();

foreach($categoryIds as $categoryId) {
    $category = Mage::getModel('catalog/category')->load($categoryId);
    echo $category->getName();
    echo $category->getUrlPath();
 }
like image 94
Adam McCombs Avatar answered May 01 '23 15:05

Adam McCombs