I am trying to get category names in category path based on product id in magento.
Suppose My Product Id = 1 and In that I define category5 (id = 5) and I get category path like 2/3/5. Instead of this type of category path I need category path like category2/category3/category5. That means I need category names in path Instead of category Ids. I got this by using following code but its takes so much time. I need to reduce processing time.
Please give me suggestions for how can I reduce process time.
$category_model = Mage::getModel('catalog/category');
$product_model = Mage::getModel('catalog/product');
$all_cats = array();
$product_model->reset();
$_product = $product_model->load($entityId);
$all_cats = $product_model->getCategoryIds($_product);
$main_cnt = count($all_cats);
$cat_str_main = '';
$j = 0;
foreach($all_cats as $ac)
{
$root_category = $category_model->load($ac);
$cat_path = $root_category->getPath();
$cat_arr = explode("/",$cat_path);
$cnt = count($cat_arr);
$cat_str = '';
$main_str = '';
$i=0;
foreach($cat_arr as $ids)
{
$root_category = $category_model->load($ids); //load root catalog
if($i == 2)
{
$cat_str = $category_model->getName();
}
else if($i > 2)
{
$cat_str = $cat_str."/".$category_model->getName();
}
$i = $i+1;
}
if($j < 1)
{
$cat_str_main = $cat_str;
}
else
{
$cat_str_main = $cat_str_main .",".$cat_str;
}
$j = $j+1;
}
Thanks.....
You should use the category collection instead of load for each category to reduce the database queries.
Edit: I have written you a code sample. I assume you have the category ID of the category of which you want to get the names of the path as $categoryId:
$category = Mage::getModel('catalog/category')->load($categoryId);
$collection = $category->getResourceCollection();
$pathIds = $category->getPathIds();
$collection->addAttributeToSelect('name');
$collection->addAttributeToFilter('entity_id', array('in' => $pathIds));
$result = '';
foreach ($collection as $cat) {
$result .= $cat->getName().'/';
}
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