Ben Edwards
Ben Edwards

Reputation: 168

(1.9) Get ID's of all a product's categories (on product page)

So this week I managed to break my site by attempting to get the ID of the current category within the product page (catalog/product/view.phtml), using the following code

$category_id = Mage::registry('current_category')->getId();

This actually works fine if you navigate into the product through the generic navigation, but when reaching a product from the front page 'featured products' link, everything falls over - presumably because I'm asking for a category ID when i'm not in a category.

What i'd like to know is how i can fetch an array of IDs of all the categories to which the current product belongs.

Upvotes: 0

Views: 2145

Answers (2)

larp
larp

Reputation: 1067

Try this:

//This will get the info of current product.

$product = Mage::registry('current_product'); 

$prodID = $product->getId();

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

$categoryIds = $_product->getCategoryIds();

foreach($categoryIds as $categoryIds1) {    
   $_category = Mage::getModel('catalog/category')->load($categoryIds1);

//get all category ID in the current product.

   echo $category_name = $_category->getId();

//get all the Category Name of the Product.

   echo $category_name = $_category->getName();
}

Upvotes: 0

Toan Tran
Toan Tran

Reputation: 54

Magento default catalog/product model has default method to get all category ids of a product. Just try with

$product = Mage::getModel('catalog/product')->load($id);
$categoryIds = $product->getCategoryIds();

Upvotes: 3

Related Questions