Magento - get specific category name from product

2019-09-02 21:19发布

问题:

This is my code:

$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();

foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
     if ($category_id == 3 || 4 || 5 || 6 || 7 || 8) {
          echo $_cat->getName();
     }
}

I want to display only one specific category(cat) name:

If the product (it is always just one which is displayed) is in a specific cat (the specific cat ids are: 3,4,5,6,7,8) it should display the cat name (but only the cat name of one of these ids).

Every product is in only one of these cats but it has more cats (child cats and default cat).

For Example: I have a product from cat 4. My code displays all cat names (default, cat 4 and the child cats), but i just want the name of cat 4. My if expression doesn't work. Has anybody an idea how to fix this?

回答1:

You want to check whether your variable is part of a set, so it is wise to build an array and check whether the value is in the array:

$elements = array(3, 4, 5, 6, 7, 8);
$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();

foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id);
     if (in_array($category_id, $elements)) {
          echo $_cat->getName();
     }
}


回答2:

You can get Magento category name or category id of particular product by product id. You following code:

    $_proId  = $this->getProduct()->getId();
    $product = Mage::getModel('catalog/product')->load($_proId);
    $cats = $product->getCategoryIds();

    foreach ($cats as $category_id) {
        $_cat = Mage::getModel('catalog/category')->load($category_id) ;
        $currentCategory = $_cat->getId();
    }


标签: php magento