0

Hi my issue is if I go to a product with the full url as in:

mysite.com/mycategory/myproduct

My code pulls back its top level category.

However, if I go to: mysite.com/myproduct

The product displays but with no breadcrumbs and my code to grab the category ID fails.

My code is:

<?php
    $category = Mage::registry('current_category');
    while ($category->getLevel() != 2) {
    $category = Mage::getModel('catalog/category')->load($category->getParentId());
}
    $catid = $category->getId();
?>

I am unsure what to do do I need the change my code to work universally or? Ver 1.9.2.2

1

What category would you expect to see on this page? Certainly not myCategory? Or would you expect a different breadcrumb path of Home -> Product Name?

Either way to pull a "valid" category ID from the product you can go with something like

$category = Mage::registry('current_category');
$product = Mage::registry('current_product');
$catid = null;

if ($category instanceof Mage_Catalog_Model_Category) {
    while ($category->getLevel() != 2) {
        $category = Mage::getModel('catalog/category')->load($category->getParentId());
    }
    $catid = $category->getId();
} else if ($product instanceof Mage_Catalog_Model_Product) {
    $categoryIds = $product->getCategoryIds();
    if (is_array($categoryIds) && count($categoryIds) >= 1) {
        $catid = $categoryIds[0];
    }
}

The above will attempt to get catid from the current_category. If we're on a PDP without a current_category then it will attempt to get the first valid category id from current_product.

Your above code also looks pretty inefficient (load within a loop of any kind is a definite no-no) but I can't see your full code to help refactoring.

  • Thank you for this! I am also trying to pull in image, name etc using this $_category = Mage::getModel('catalog/category')->load($catid); $_category->getImageUrl(); however this doesn't work on some pages and I am guessing I have done something wrong similar to above? Can you advise? – KiwisTasteGood Jan 27 '16 at 15:42

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.