The simplest way to display custom attributes is to enable them on product view pages, where they normally show up as a table. Design files can be edited to display custom product attributes elsewhere on the product view page. When a Magento product object gets loaded in a template file, any custom attributes that have been added to products are also accessible. The method used to retrieve the values depends on the type of attribute. For drop-down attributes you can use the following code:
<?php echo $_product->getAttributeText(’attribute_name’) ?>
and for all other attribute types:
<?php echo $_product->getAttributeName() ?>
The above code will only return values on product view pages. If you would like to use these elsewhere, then you will need to make further modifications. Magento provides a backend setting to decide if the attribute is to be made available in product listings, such as category pages. Setting "Used in product listing" to yes
makes the attribute values accessible on category and search pages.
To access custom attributes on any other page requires modifications to the way the product collections are loaded. The functions responsible for loading products are:
public function getItemCollection()
public function getProductCollection()
Which of the two is used will depend on the context. To load a custom attribute you need to modify the above functions to include an addAttributeToSelect('test_attribute')
function call. Often Magento code already has addAttributeToSelect
calls, hence searching for those calls in the relevant module is one way to find which function needs to be modified. For example, if you wanted to use a custom attribute, say recommended_retail_price
, in the compare products sidebar, you would need to modify public function getItemCollection()
in:
app/code/core/Mage/Catalog/Helper/Product/Compare.php
and change the following code:
$this->_itemCollection->addAttributeToSelect('name')
->addUrlRewrite()
->load();
to
$this->_itemCollection->addAttributeToSelect('name')->addAttributeToSelect('recommended_retail_price')
->addUrlRewrite()
->load();
Only then can you use <?php echo $_product->getRecommendedRetailPrice() ?>
in the respective phtml template file to show the value on the compare sidebar.
Equipped with this knowledge, it's easy to leverage flexibility of the product attribute system for extended functionality on the Magento frontend.