Magento 1 - get category ID from product ID

Elamurugan picture Elamurugan · Dec 10, 2010 · Viewed 29k times · Source

In magento how to get the category id of each product from its product ID.

   $items    = $request->getAllItems();
    $c           = count($items); 

    for ($i = 0; $i < $c; $i++) {
        if ($items[$i]->getProduct() instanceof Mage_Catalog_Model_Product) {

            if ($items[$i]->getProduct()->getId()) {
               $this->_dhlAllowed    = false;
              }
        }
    }

Here $items[$i]->getProduct()->getId() returns product ID. I want its category ID.

Answer

Andrey Korolyov picture Andrey Korolyov · Jan 9, 2011
public function getProductCategory() {
    /* @var $product Mage_Catalog_Model_Product */
    $product = Mage::registry('current_product');
    if ($product->getId()) {
        $categoryIds = $product->getCategoryIds();
        if (is_array($categoryIds) and count($categoryIds) >= 1) {
            return Mage::getModel('catalog/category')->load($categoryIds[0]);
        };
    }
    return false;
}