Getting Attribute Values

There are a few ways to get get attribute values in Magento:

<?php
$product->getAttributeCode();

$product->getData(attribute_code);

These two methods do the same thing, however if the attribute is a type of select or multiselect then the ID of the value will be returned rather than the text of the attribute.

For these methods, the frontend attribute can be obtained from the product and used to get the attribute value:

<?php
// Get the type of the attribute as dictated by the attribute's *frontend_model* field.
// This will be a Mage_Catalog_Model_Resource_Eav_Attribute model:
$attr = $product->getResource()->getAttribute($attributeName);

// Get the value from the frontend type of the attribute. The frontend type is dictated by the frontend_model column in the eav_attribute table.  By default, this will be Mage_Eav_Model_Entity_Frontend_Default if the frontend_model field is empty.

$val = $attr->getFrontend()->getValue($product);

Note If an attribute value is not set, (I.e. NULL) the frontend attribute will return “No”. This happens in the Mage_Eav_Model_Entity_Attribute_Frontend_Abstract class’ getValue method:

 if (!$valueOption) {
    $opt     = Mage::getModel('eav/entity_attribute_source_boolean');
    $options = $opt->getAllOptions();

    if ($options) {
        foreach ($options as $option) {
            if ($option['value'] == $value) {
                $valueOption = $option['label'];
            }
        }
    }
}

– It uses the “eav/entity_attribute_source_boolean” and defaults to one of the values set within in.

getAttributeText

Another way to get the value of a select attribute is to use

<?php
$product->getAttributeText(attribute_name);

This will use the attribute’s source_model (typically used in getting all possible values in adminhtml), and looks up the text of the attribute based on the value’s ID (this is set on the product’s data array):

<?php
   public function getAttributeText($attributeCode)
    {
        return $this->getResource()
            ->getAttribute($attributeCode)
                ->getSource()
                    ->getOptionText($this->getData($attributeCode));
    }

Outputting Attributes

Product attributes have various non-standard EAV options to control how they’re output, such as escaping HTML characters. To honour these settings, product attributes should be passed through the catalog/output helper:

<?php
$helper = Mage::helper('catalog/output');

echo $helper->productAttribute($product, $value, 'attribute_name');

Outputting a list of Attributes

Magento provides a block to output product attributes on the product detail page, provided they’re set to be visible on front. Use the Mage_Catalog_Block_Product_View_Attributes. If an attribute isn’t set, it will return “N/A”, if this is not required then this could be overridden and this line replaced with a continue;.