6

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.

Black
  • 18,150
  • 39
  • 158
  • 271
Elamurugan
  • 3,204
  • 13
  • 59
  • 104
  • 2
    $items[$i]->getProduct()->getCategoryIds() ; This returns category ID in one server but in not another server. Any idea? – Elamurugan Dec 11 '10 at 10:23
  • Did you tried reindexing the flat category tables on the server? This kind of strange things are commonly associated with an outdated (or corrupted) index. – mcmil Dec 11 '10 at 18:16

3 Answers3

6
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;
}
Andrey Korolyov
  • 996
  • 6
  • 10
2
Mage::registry('current_product')->getCategoryId();

this way, category id of a current product can be get.

R T
  • 4,369
  • 3
  • 38
  • 49
2

suppose if you want all category ids from current product id you can get from

Mage::registry('current_product')->getCategoryIds();

it may help you

Keyur Shah
  • 11,043
  • 4
  • 29
  • 48