Magento : Category Name instead of category ids in category path.

12,102

Solution 1

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().'/';
}

Solution 2

I think you should look into magento catalog url rewrites which handles this issue for you... in your magento admin it should be in catalog >> URL rewrite management

Edit:

Because you want to do it in some other page you can simply do:

$store = Mage::app()->getStore();

$product_url = $store->getBaseUrl().$product->getUrlPath();

$category_url = $store->getBaseUrl().$category->getUrlPath();
Share:
12,102
user123
Author by

user123

Updated on June 30, 2022

Comments

  • user123
    user123 almost 2 years

    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.....