1

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...
3

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();
  • Hmm, the theme I'm using doesn't appear to have an attributes.phtml file as the demo theme does. I tried to copy the demo theme code and place it into my theme's description.phtml file and it doesn't display anything – user3482 Mar 5 '14 at 14:30

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.