Magento – how to echo custom attribute value in crosssell.phtml in magento

cross-sellscustom-attributesmagento-1.7

this is my crosssell.phtml code:

<div class="crosssell">
    <p><?php echo $this->__('THIS PRODUCT IS ALSO AVAILABLE IN ') ?></p>
    <ul id="crosssell-products-list">
    <?php foreach ($this->getItems() as $_item): ?>
        <li class="item">              
            <div class="product-details">
                <h3 class="product-name"><a href="<?php echo $_item->getProductUrl() ?>"><?php echo $this->htmlEscape($_item->getName()) ?></a></h3>                       
            </div>
        </li>
    <?php endforeach; ?>
    </ul>
<script type="text/javascript">decorateList('crosssell-products-list', 'none-recursive')</script>

Now I have a custom attribute say 'colour'. I want to show this custom attribute value in crossell.phtml in the foreach loop.
My attempt so far:

<?php echo $attr= $_item->getResource()->getAttribute('colour')->getFrontend()->getValue($_item); ?>

Please help. Thanks in advance.

Best Answer

config.xml

Magento checks this XPath in the config.xml to get the attributes which are loaded automatically with a collection:

/config/frontend/product/collection/attributes

Example: app/code/core/Mage/Catalog/etc/config.xml:721

To add an attribute to the cart page, you need to load the attribute during the product loading of the quote_item_collection, this can be done via XML too, the XPath is:

/config/global/sales/quote/item/product_attributes

Observer

Implement an observer and listen to the event catalog_block_product_list_collection for adding attributes to the product list block and on catalog_product_collection_load_before to add attributes to ALL collection loadings.

We have plenty of explanation here on magento SE and in the web how to implement an observer, e.g. from apptha.

Inside the observer method we just have to add things to the collection:

public function catalogBlockProductListCollection(Varien_Event_Observer $observer) {
    $collection = $observer->getCollection();
    $collection->addAttributeToSelect('MY_ATTRIBUTE');
    $collection->addAttributeToFilter('size', 'XL'); // you can although filter if you want!
}

Attribute used_in_product_list

The third alternative is (as @Christian-Ducrot describes) to change the setting of the attribute for used_in_product_listing to yes.

This can either be done in the attribute backend, while creating an attribute with Mage_Catalog_Model_Resource_Setup::addAttribute and setting used_in_product_listing to 1 or later with Mage_Catalog_Model_Resource_Setup::updateAttribute