Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento 1 - get category ID from product ID

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.

like image 369
Elamurugan Avatar asked Dec 10 '10 21:12

Elamurugan


People also ask

How to get product category id in Magento?

You need to instantiate Magento\Catalog\Model\ProductCategoryList class in your __construct() method to get category ids for a product. Here 5 and 12 is category id of the product with id is 10. The result will be an array of category ids for the products.

How do I get a product collection in Magento 1?

php $_productCollection = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToSort('created_at', 'DESC') ->addAttributeToSelect('*') ->load(); foreach ($_productCollection as $_product){ echo $_product->getId().


2 Answers

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;
}
like image 164
Andrey Korolyov Avatar answered Sep 18 '22 12:09

Andrey Korolyov


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

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

like image 20
R T Avatar answered Sep 20 '22 12:09

R T