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.
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.
php $_productCollection = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToSort('created_at', 'DESC') ->addAttributeToSelect('*') ->load(); foreach ($_productCollection as $_product){ echo $_product->getId().
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;
}
Mage::registry('current_product')->getCategoryId();
this way, category id of a current product can be get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With