Magento – Loop Magento Custom Attributes in Product View Description

attributesdropdown-attributemagento-1.7multiselect-attributeproduct-attribute

I'm trying to figure out a way to best display custom attributes on the product view page.

Currently I'm doing something like this:

if (($_product->getCollectionName()) && ($_product->getResource()->getAttribute('collection_name')->getIsVisibleOnFront() == '1')) 
{
     echo $_product->getResource()->getAttribute('collection_name')->getFrontendLabel() . ': ' . $_product->getCollectionName();
} 

if (($_product->getColor()) && ($_product->getResource()->getAttribute('color')->getIsVisibleOnFront() == '1')) 
{
     echo $_product->getResource()->getAttribute('color')->getFrontendLabel() . ': ' . $_product->getColor();
} 

This continues for all 95 custom attributes.

Does Magento have any built-in functions to simplify this code? Is there a way to loop through all the attributes assign to the product?

A few things to keep in mind:

  • I need to check if the attribute is set to visible on the frontend
  • I need to show the attribute label only when the attribute has a value for the product
  • Attributes vary in type – text, multi-select, dropdown…

Best Answer

Magento already has a block that displays the attributes in the view page. It is called Mage_Catalog_Block_Product_View_Attributes. See this as demo (additional information section).
All the attributes that have is_visible_on_front are displayed in that section.

The only down side is that it shows event he attributes that don't have a value.
To overcome this, just rewrite the method getAdditionalData in that block and replace

if (!$product->hasData($attribute->getAttributeCode())) {
    $value = Mage::helper('catalog')->__('N/A');
} elseif ((string)$value == '') {
    $value = Mage::helper('catalog')->__('No');
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
    $value = Mage::app()->getStore()->convertPrice($value, true);
}

with

if (!$product->hasData($attribute->getAttributeCode())) {
    continue;
} elseif ((string)$value == '') {
    continue;
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
    $value = Mage::app()->getStore()->convertPrice($value, true);
}

EDIT
But just in case you need it for something...here is how you can get the product available attributes

$attributes = $product->getAttributes();
Related Topic