Magento 1.9.1.0 – How to Display Most Viewed Products on HomePage

magento-1.9product

I need to display the most viewed products on home page.without any plugin installation. please help me!

Best Answer

Use below code to get Most Viewed products collection :

<?php
$storeId = Mage::app()->getStore()->getId();

$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->setStoreId($storeId)
    ->addStoreFilter($storeId)
    ->addViewsCount()
    //->setPageSize($totalPerPage)
    ;
?>

For more details, check List Popular Products

UPDATE : In admin, go to CMS > Pages, edit Homepage.

-- In Content area, add this line : {{block type="catalog/product" template="catalog/product/most-viewed.phtml"}} and SAVE.

-- Now create a new template file at /app/design/frontend/PACKAGE/THEME/template/catalog/product/, and name it most-viewed.phtml

-- Add this code in most-viewed.phtml file, (this will show max 10 products, edit $totalPerPage variable as you require)

<?php
$totalPerPage = 10;
$storeId = Mage::app()->getStore()->getId();
$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')
    ->setStoreId($storeId)
    ->addStoreFilter($storeId)
    ->addViewsCount()
    ->setPageSize($totalPerPage)
    ;
?>
<?php $_collectionSize = $_productCollection->count(); ?>

<?php if ($_collectionSize) { ?>
    <h2 class="subtitle">Most Viewed Products</h2>
    <ul class="products-grid">
        <?php
        foreach ($_productCollection as $_product):
        $image_url = $this->helper('catalog/image')->init($_product, 'thumbnail')->setWatermarkImageOpacity(0)->keepFrame(false)->resize(200,200);
        $alt = $this->htmlEscape($this->stripTags($this->getImageLabel($_product, 'small_image'), null, true));
        ?>
        <li class="item">
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>">
                <img src="<?php echo $image_url; ?>" alt="<?php echo trim($alt)? $alt: $this->htmlEscape($this->stripTags($_product->getName())); ?>" />
            </a>
            <div class="product-info">
                <h2 class="product-name">
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>">
                        <?php echo trim($alt)? $alt: $this->htmlEscape($this->stripTags($_product->getName())); ?>
                    </a>
                </h2>
            </div>
        </li>
        <?php endforeach; ?>
    </ul>
<?php } ?>
Related Topic