Magento category ID from product ID


Magento category ID from product ID : Sometimes we need to get the category id from product id. Mage::registry(‘current_product’); is used to get the category of current product ie. selected product. Here in this tutorial we are going to explain the methods how you can get category id from product id.


Magento category ID from product ID

First load the product using the catalog product model then check if product is loaded and get category ids as below –

:

$productId = 100;
$product = Mage::getModel('catalog/product')->load($productId);
if ($product->getId()) {
        $categoryIds = $product->getCategoryIds();
        if (is_array($categoryIds) and count($categoryIds) >= 1) {
            $cat = Mage::getModel('catalog/category')->load($categoryIds[0]);
			echo $cat->getId()."<br>";
        }else{
        echo "No Category Found.";
       }
    }

The above example will give the category ids of the selected product as above.


Advertisements

Add Comment

📖 Read More