Recently whilst working on a project that used the Magento e-commerce Platform I needed to display custom attributes within transactional e-mails.
After spending a day looking into the documentation and making the required changes I thought it would be well worth my time writing a brief entry detailing the steps I took for future reference, and hopefully for the benefit of others.
To avoid confusion I removed all irrelevant HTML/PHP from the examples below.
1. Adding the attributes
My requirement was for every product to have an age-range. So I created two custom attributes and added them to the "Default" Attribute Set. The attributes were:
- "Lowest Age" (attribute code of "lowest_age")
- "Highest Age" (attribute code of "highest_age")
2. Modify the Transactional E-Mail template
I then created a Transactional E-Mail, and made the relevant changes to the settings so it was used. The template consisted of the following code...
<body>
<h1>Hello, {{htmlescape var=$order.getCustomerName()}} </h1>
<p>Thank you for your order from {{var store.getFrontendName()}}. </p>
<h2>Order Details</h2>
{{block type='core/template'
area='frontend'
template='/emails/product_details.phtml'
order=$order}}
</body>
3. Create the product template file
The Transactional E-Mail template above points to a ".PHTML" template file, which I create in this stage. The file-name of the template is "product_details.phtml" and for my setup it needs to be located at "/app/design/frontend/default/default/template/emails/". The contents of this file is pretty self explanatory...
<!-- /app/design/frontend/default/default/template/emails/product_details.phtml -->
<?php $_order = $this->getOrder(); ?>
<table border="1">
<thead>
<tr>
<th bgcolor="#d9e5ee">Product Name</th>
<th bgcolor="#d9e5ee">Age Range (Years)</th>
<th bgcolor="#d9e5ee">Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($_order->getAllItems() as $_item): ?>
<tr>
<td><?php echo $_item->getName() ?></td>
<td>
<?php
$_product = Mage::getModel('catalog/product');
$_product ->load($_item->getProductId());
echo $_product->getLowestAge()." - ".$_product->getHighestAge();
?>
</td>
<td><?php echo $_order->formatPrice($_item->getPrice()) ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
Result
After following the extremely brief steps above you should be receiving e-mails that contain custom attributes.