简体   繁体   中英

Getting the last sub-category of a product in magento

I having been searching for days to get the last subcategory of a product in magento.

Actually what i have to do is display the last subcategory the product is placed in. for example i have plastic and glass as products. I want to display the last subcategory ie cups or plates.

|Party
--|boys
----|batman
--------|cups
-----------|plastic
-----------|glass
--------|plates
----|Superman

i have edited the list.phtml file, i can get the category id's and name from the array but they are all mixed up. So there is no way to figure out which one is the last category. Is there any default functionality in magento? or someone be kind enough to help me out? Thanks in advance.

Edit

Okay, from your description it sounds like you want to get the child categories from the current category you're in. (IE Get cups and plates while in batman category view).

The following should be just about as little as you need to get the current children.

<?php
    $_helper = Mage::helper('catalog/category');
    $children = Mage::registry( 'current_category' )->getChildrenCategories();
?>
<ul>
    <?php foreach( $children as $child ): ?>
        <li><a href="<?php echo $_helper->getCategoryUrl($child); ?>"><?php echo $child->getName() ?></a></li>
    <?php endforeach; ?>
</ul>

Previous Answer(s)

It's a little roundabout, but this can get you the parent category id from a product object.

//If you don't have a product to start with, load by ID.
$_product = Mage::getModel( 'catalog/product' )->load($id);

//Assign Category Model
$categoryModel = Mage::getModel( 'catalog/category' );

//Get Array of Category Id's with Last as First (Reversed)
$_categories = array_reverse( $_product->getCategoryIds() );

//Get Parent Category Id
$_parentId = $categoryModel->load($_categories[0])->getParentId();

//Load Parent Category
$_category = $categoryModel->load($_parentId);

//Do something with $_category
echo $_category->getName();

It works better when the product only has one category Id assigned to it. You may not get the category you want if multiple categories have been assigned to that one product.

Also, you can get it a slightly quicker way, but this method doesn't work if the product was searched for:

$_category = Mage::getModel( 'catalog/category' )->load( Mage::registry( 'current_category' )->getParentId() );

I didn't test the line above, but it should work. Only if the product was reached by browsing through the categories though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM