Wednesday 24 June 2015

Magento get product custom attribute value by attribute code

Wrong way to do it

In many Magento template files, $_product, which is an instance of Mage_Catalog_Model_Product, can be found and used to obtain the product details. In some places, we can get custom attribute value by $_product->getMyCustomAttribute(), but we will get NULL if $_production is in the loop of a product collection, which is not what we expected.

Right way to do it

If $_product is in the loop of a product collection, we would have to load the product manually and then get the attribute value as below:
Mage::getModel('catalog/product')->load($_product->getId())->getMyCustomAttribute()

If $_product is obtained by Mage::getModel('catalog/product')->load($_product->getId()), we can absolutely get the attribute value by $_product->getMyCustomAttribute()

No comments:

Post a Comment