Get custom attribute value in Magento

Get custom attribute value in Magento

So you have created some custom attributes for your Magento products and now you want to fetch their values. Magento provides a function getAttributeText that takes attribute code and returns you the attribute value.

echo $_product->getAttributeText('custom_attribute_code');

Problem:
Above method returns you attribute value only when the attribute was registered, but it will return a fetal error if the attribute was not already registered.

Fatal error: Call to a member function getSource() on a non-object in D:\..\app\code\core\Mage\Catalog\Model\Product.php on line 1389

Safe way to get custom attribute value:

To avoid fetal errors and crashes, here is safe way to get custom attribute value. If you get custom attribute values by following below procedure, your site will not crash even when the attribute was not yet registered.

$attribute = $_product->getResource()->getAttribute('custom_attribute_code');
if ($attribute)
{
	echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}

This code will first checks if the attribute code exists and gets its value if its there.

Author: Tahir Yasin

Tahir is a Passionate Web Developer from Lahore, Pakistan and a guy with NEVER-STOP-LEARNING attitude who keeps an eye on emerging technologies and customer trends.

2 thoughts on “Get custom attribute value in Magento”

  1. $cartItems = Mage::getSingleton('checkout/session')
              ->getQuote()
              ->getAllItems();
        foreach ($cartItems as $item) {
            $ean = Mage::getModel('catalog/product')->load($item->getProduct()->getId())->getEan();
            echo $ean;
        } 
    

    Where getEan is the name of my attribute with the first character as a capital letter.
    this may help you to display the customized attribute value

Leave a Reply

Your email address will not be published. Required fields are marked *