Magento: Unable to select custom attribute on product collection

Problem:

I had added a new product attribute. Suppose the attribute code is ‘test’. I have been trying to fetch/select that newly added product attribute. Here is my Magento collection code:-


$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('test')
->addAttributeToFilter('url_key', 'SOME_URL_KEY')
->getFirstItem();

I don’t see the attribute ‘test’ when I print the collection data.


echo "<pre>"; 
print_r($collection->getData());
echo "</pre>";

Cause:

The attribute is not fetched because my shop had ‘Product Flat Data’ enabled. And the attribute is not included in the Flat Product Index.

Solution:

To include the attribute (our attribute code is ‘test’) in flat index, we need to add the following code in config.xml file of your custom module:


<config>
    <frontend>
         <product>
              <collection>
                   <attributes>
                      <test />                                            
                   </attributes>
              </collection>
          </product>
    </frontend>
</config>

After that, we need to reindex Product Flat Data.

– Login to Admin
– Go to System -> Index Management
– Reindex ‘Product Flat Data

Now, the above collection code should be able to select your custom attribute ‘test‘.

Thanks to Ivan Chepurnyi for the solution over here: http://stackoverflow.com/a/11798502/327862

Hope it helps. Thanks.