The Problem
On a recent Magento project I wanted to create featured products on the home page but limit it to display only three. I then wanted to include a “View More” link which would take you through to the rest of the featured products. I also wanted to be able to specify which three featured products were to appear on the home page.
The Solution
1) I created a new category (hidden from navigation) called Featured Products and added all my featured products to this category
2) I then added a new “yes/no” attribute called “Featured on Homepage” and added it to my default set
3) I Created a new template file called “featured-home” this included all my product attributes and structure I wanted to use. I used /template/catalogue/product/list.phtml as a guide but heavily edited it to my needs.
4) At the top of the document I added the following code which would filter those products marked as “Featured on Homepage”.
<?php
// some helpers
$_helper = $this->helper('catalog/output');
$storeId = Mage::app()->getStore()->getId();
$catalog = $this->getLayout()->createBlock('catalog/product_list')->setStoreId($storeId);
// get all products that are marked as featured
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('featured');
$collection->addFieldToFilter(array(
array('attribute' => 'featured', 'eq' => true),
));
// if no products are currently featured, display some text
if (!$collection->count()) :
?>
<p class="note-msg"><?php echo $this->__('There are no featured products at the moment.') ?></p>
<?php else : ?>
5) I edited my loop (that loops through my products) to read
<?php
$i=0; foreach ($collection as $_product) :
$_product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($_product->getId());
if ($i > 2) break;
?>
This limits the loop to display just 3 products.
6) I then added :
<?php $i++; ?>
Just before the end of my else statement.
7) To display my products on my home page I went to CMS->PAGES->HOME inside Magento and added the following block into the design tab.
<reference name="content">
<block type="core/template" name="home-featured" template="catalog/product/featured-home.phtml"/>
</reference>
8) I could then add a link through to my featured products category from my featured-home.phtml so visitors can now see all the latest products.
Job done!