3

I'm trying to get breadcrumbs working on product page. I need to display current category and url

template file: catalog/product/view.phtml

I have tried the following:

$categories = $_product->getCategoryIds();
foreach($categories as $categoryId){
    $_category = Mage::getModel('catalog/category')->load($categoryId);
    echo $_category->getName();
    if($_category->getIsActive()){
        echo "yes\n";
    }

}

above code works, but it outputs all categories.

I have tried the following, but it didn't work

$current_cat = $this->getCurrentCategory();
echo "cat:\n";
print_r($current_cat);
//$category = Mage::registry('current_category');
//print_r($category->getName());
$c = Mage::getModel('catalog/layer')->getCurrentCategory();
print_r($c->getName());

can you suggest how to get current category? or is there alternative solution?

  • 5
    Before answering your query, why are you trying to control your breadcrumb trail from your product view template file? – zigojacko Jan 22 '14 at 17:17
6

Try Using this

<?php $cat_id = Mage::getModel('catalog/layer')->getCurrentCategory()->getId(); ?>
<?php $category = Mage::getModel('catalog/category')->load($cat_id); ?>
<?php echo $category->getName(); ?>
3

It's not possible to select active category because product can belong to multiple categories. For example, wristbands belong to 'girls accessories' and 'guys accessories'. One possible solution is to selected first element of categories array with 2nd level.

$categories = $_product->getCategoryIds();
foreach($categories as $categoryId){
    $_category = Mage::getModel('catalog/category')->load($categoryId);
    $categoryData = $_category->getData();
    if($categoryData['level']==2){
        $currentCategory = $_category;
        break;
    }
}
  • Be cautious as this uses a load() in a loop which is bad practice when it comes to performance. – B00MER Nov 17 '15 at 0:36
3

As @VladVinnikov wrote, products can belong to multiple categories so there might be no unambiguous "current category".

Except when there is

Products can have different URLs dependent on where they are linked:

  • example.com/product.html
  • example.com/category1/product.hml
  • example.com/category2/subcategory/product.html

If the product page was opened from a category with the category specific URL, this category is available with Mage::registry('current_category').

So to answer the question, how to get its name and url:

if ($category = Mage::registry('current_category')) {
    $name = $category->getName();
    $url = $category->getUrl();
} else {
    // either show nothing or fall back to load the product categories and pick one
}

and how to display them:

<a href="<?php echo $this->quoteEscape($url) ?>"><?php echo $this->escapeHtml($name) ?></a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.