CMS Block Widgets – Individual Product Templates

cmsproductstatic-blocktemplatewidget

I'm working on a CMS Block to show featured products on the home page. I set up my own template file which loads $this->getProduct() for the data.

The problem I'm having is that I'm using the catalog/product_view block type and it only loads one product, so if I repeat the widget multiple times with multiple product IDs, it will only repeat the first one (I'm guessing because the class constructor gets the product in the constructor, and Magento won't load it more than once per request)

For example, this:

{{block type="catalog/product_view" product_id="1234" template="page/html/featured/product.phtml"}}
{{block type="catalog/product_view" product_id="5678" template="page/html/featured/product.phtml"}}

When repeated twice will display the product with ID 1234 twice, using this code:

app/design/frontend/mypackage/page/html/featured/product.phtml

<?php 
$p = $this->getProduct();
$img = $p->getImageUrl();
$description = $p->getShortDescription();
$name = $p->getName();
$link = $p->getProductUrl();

echo "<div style='display:inline-block;width: 20%;float: left;'>
        <a href ='$link'><img style='width:80%;margin:0 10%;' src='$img' />
        <div class='product-name'>$name</div>
        </a>
        <div class='home-product-description'>$description</div>
    </div>";

Is there a different block type (model) that I can use to load individual products, perhaps as a singleton? I would like to be able to get a different product for each time I call the widget using the same template to display the output. The only other option I could think of was to load a collection of a specified category in the template itself, but naturally that defeats the purpose of flexibility that the CMS offers.

Best Answer

There's a widget for that! In your CMS page,

{{widget type="catalog/product_widget_link"
         anchor_text="[Optional: CUSTOM LINK TEXT]"
         template="catalog/product/widget/link/link_block.phtml"
         id_path="product/223552"}}

Then customize app/design/frontend/base/default/template/catalog/product/widget/link/link_block.phtml. I use something like this:

<?php

$_product = $this->getProduct();
$_image = '';
$_price = '$' . money_format('%n', $_product->getFinalPrice());

if ($_product) {
    $_image = Mage::helper('catalog/image')->init($_product, 'thumbnail')
        ->keepAspectRatio(true)
        ->keepFrame(true)
        ->resize(115,115)
        ->__toString();
}
?>
<div class="item">
    <a <?php echo $this->getLinkAttributes() ?>>
        <img src="<?php echo $_image; ?>" alt="<?php echo $this->htmlEscape($this->getAnchorText()); ?>" style="border:0" />
        <?php echo nl2br($this->htmlEscape($this->getAnchorText())); ?><br />
        <b><?php echo $_price; ?></b>
    </a>
</div>
Related Topic