Output the id of the parent category in Magento
During the development process we come across all sorts of specific tasks that require some creative thoughts to achieve the end result. Learning to think creatively when developing for Magento can not only save you time, but unlock doors to many other possibilities.
We were presented with one of these tasks recently that i thought we would share in the hope it would save someone else some time and maybe spark of a new trail of thought for new possibilities in your Magento store.
Being able to get the ID of the parent category the user is in was the solution to our problem and i’m sure can be used in many different ways. Using this ID we were able offer a different navigation to the user on the iPhone theme we were developing for one of our websites. If you have ever developed an iPhone theme in Magento or any other ecommerce framework you will be familiar with the obstacle of how best to display the navigation in a clear and concise way to the user. Using the parent ID, we were able to show just the categories in the drop down navigation that related to the parent category you are in, with a simple “back to main menu” link to start the user on their journey again.
Here’s the code you will need to get the parent ID.
To find the parent ID you first need to establish the ID of current category you are in.
<?php
$_cat = new Mage_Catalog_Block_Navigation();
$curent_cat = $_cat->getCurrentCategory();
$curent_cat_id = $curent_cat->getId();
?>
With this information you can then find the parent ID and echo out on to the front-end view.
<?php
$parentId=Mage::getModel(‘catalog/category’)->load($curent_cat_id)->getParentId();
echo $parentId; // $parentId will print your current category’s parent Id
?>